Python 基础语法(四)
本文内容纲要:
--------------------------------------------接Python基础语法(三)--------------------------------------------
十、Python标准库
Python标准库是随Pthon附带安装的,包含了大量极其有用的模块。
**1.sys模块**sys模块包含系统对应的功能
-
sys.argv---包含命令行参数,第一个参数是py的文件名
-
sys.platform---返回平台类型
-
sys.exit([status])---退出程序,可选的status(范围:0-127):0表示正常退出,其他表示不正常,可抛异常事件供捕获
-
sys.path---程序中导入模块对应的文件必须放在sys.path包含的目录中,使用sys.path.append添加自己的模块路径
-
sys.modules---Thisisadictionarythatmapsmodulenamestomoduleswhichhavealreadybeenloaded
-
sys.stdin,sys.stdout,sys.stderr---包含与标准I/O流对应的流对象
s=sys.stdin.readline()
sys.stdout.write(s)
**2.os模块**该模块包含普遍的操作系统功能
- os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'
- os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径
- os.getenv()和os.putenv()函数分别用来读取和设置环境变量
- os.listdir()返回指定目录下的所有文件和目录名
- os.remove()函数用来删除一个文件
- os.system()函数用来运行shell命令
- os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
- os.sep操作系统特定的路径分割符
- os.path.split()函数返回一个路径的目录名和文件名
- os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录
- os.path.existe()函数用来检验给出的路径是否真地存在
十一、其他
**1.一些特殊的方法**
print
语句或是使用str()
的时候调用。x[key]
索引操作符的时候调用。len()
函数的时候调用。下面的类中定义了上表中的方法:
classArray:
__list=[]
def__init__(self):
print"constructor"
def__del__(self):
print"destructor"
def__str__(self):
return"thisself-definedarrayclass"
def__getitem__(self,key):
returnself.__list[key]
def__len__(self):
returnlen(self.__list)
defAdd(self,value):
self.__list.append(value)
defRemove(self,index):
delself.__list[index]
defDisplayItems(self):
print"showallitems----"
foriteminself.__list:
printitem
arr=Array()#constructor
printarr#thisself-definedarrayclass
printlen(arr)#0
arr.Add(1)
arr.Add(2)
arr.Add(3)
printlen(arr)#3
printarr[0]#1
arr.DisplayItems()
#showallitems----
#1
#2
#3
arr.Remove(1)
arr.DisplayItems()
#showallitems----
#1
#3
#destructor
**2.综合列表**
通过列表综合,可以从一个已有的列表导出一个新的列表。
list1=[1,2,3,4,5]
list2=[i*2foriinlist1ifi>3]
printlist1#[1,2,3,4,5]
printlist2#[8,10]
**3.函数接收元组/列表/字典**
当函数接收元组或字典形式的参数的时候,有一种特殊的方法,使用*和**前缀。该方法在函数需要获取可变数量的参数的时候特别有用。
由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args中。如果使用的是**前缀,多余的参数则会被认为是一个字典
的键/值对。
defpowersum(power,*args):
total=0
foriinargs:
total+=pow(i,power)
returntotal
printpowersum(2,1,2,3)#14
defdisplaydic(**args):
forkey,valueinargs.items():
print"key:%s;value:%s"%(key,value)
displaydic(a="one",b="two",c="three")
#key:a;value:one
#key:c;value:three
#key:b;value:two
**4.lambda**
lambda语句被用来创建新的函数对象,并在运行时返回它们。lambda需要一个参数,后面仅跟单个表达式作为函数体,而表达式的值被这个
新建的函数返回。注意,即便是print语句也不能用在lambda形式中,只能使用表达式。
func=lambdas:s*3
printfunc("peter")#peterpeterpeter
func2=lambdaa,b:a*b
printfunc2(2,3)#6
**5.exec/eval**
exec语句用来执行储存在字符串或文件中的Python语句;eval语句用来计算存储在字符串中的有效Python表达式。
cmd="print'helloworld'"
execcmd#helloworld
expression="10*2+5"
printeval(expression)#25
**6.assert**
assert语句用来断言某个条件是真的,并且在它非真的时候引发一个错误--AssertionError
。
flag=True
assertflag==True
try:
assertflag==False
exceptAssertionError,err:
print"failed"
else:
print"pass"
**7.repr函数**
repr函数用来取得对象的规范字符串表示。反引号(也称转换符)可以完成相同的功能。
注意,在大多数时候有eval(repr(object))==object。
可以通过定义类的__repr__方法来控制对象在被repr函数调用的时候返回的内容。
arr=[1,2,3]
print`arr`#[1,2,3]
printrepr(arr)#[1,2,3]
十二、练习
实现一个通讯录,主要功能:添加、删除、更新、查询、显示全部联系人。
1importcPickle
2importos
3importsys
4
5classContact:
6def__init__(self,name,phone,mail):
7self.name=name
8self.phone=phone
9self.mail=mail
10
11defUpdate(self,name,phone,mail):
12self.name=name
13self.phone=phone
14self.mail=mail
15
16defdisplay(self):
17print"name:%s,phone:%s,mail:%s"%(self.name,self.phone,self.mail)
18
19
20#begin
21
22#filetostorecontactdata
23data=os.getcwd()+os.sep+"contacts.data"
24
25whileTrue:
26print"-----------------------------------------------------------------------"
27operation=raw_input("inputyouroperation(add/delete/modify/search/all/exit):")
28
29ifoperation=="exit":
30sys.exit()
31
32ifos.path.exists(data):
33ifos.path.getsize(data)==0:
34contacts={}
35else:
36f=file(data)
37contacts=cPickle.load(f)
38f.close()
39else:
40contacts={}
41
42ifoperation=="add":
43flag=False
44whileTrue:
45name=raw_input("inputname(exittobackchooseoperation):")
46ifname=="exit":
47flag=True
48break
49ifnameincontacts:
50print"thenamealreadyexists,pleaseinputanotherorinput'exit'tobackchooseoperation"
51continue
52else:
53phone=raw_input("inputphone:")
54mail=raw_input("inputmail:")
55c=Contact(name,phone,mail)
56contacts[name]=c
57f=file(data,"w")
58cPickle.dump(contacts,f)
59f.close()
60print"addsuccessfully."
61break
62elifoperation=="delete":
63name=raw_input("inputthenamethatyouwanttodelete:")
64ifnameincontacts:
65delcontacts[name]
66f=file(data,"w")
67cPickle.dump(contacts,f)
68f.close()
69print"deletesuccessfully."
70else:
71print"thereisnopersonnamed%s"%name
72elifoperation=="modify":
73whileTrue:
74name=raw_input("inputthenamewhichtoupdateorexittobackchooseoperation:")
75ifname=="exit":
76break
77ifnotnameincontacts:
78print"thereisnopersonnamed%s"%name
79continue
80else:
81phone=raw_input("inputphone:")
82mail=raw_input("inputmail:")
83contacts[name].Update(name,phone,mail)
84f=file(data,"w")
85cPickle.dump(contacts,f)
86f.close()
87print"modifysuccessfully."
88break
89elifoperation=="search":
90name=raw_input("inputthenamewhichyouwanttosearch:")
91ifnameincontacts:
92contacts[name].display()
93else:
94print"thereisnopersonnamed%s"%name
95elifoperation=="all":
96forname,contactincontacts.items():
97contact.display()
98else:
99print"unknownoperation"
-----------------------------------------------------结束-----------------------------------------------------
本文内容总结:
原文链接:https://www.cnblogs.com/Peter-Zhang/archive/2011/12/26/2300943.html