Python学习系列(九)(IO与异常处理)
Python学习系列(八)( 面向对象基础)
一,存储器
1,Python提供一个标准的模块,称为pickle,使用它既可以在一个文件中存储任何Python对象,又可以把它完整的取出来,这被称为持久的存储对象。类似的,还有一个功能与之相同的模块—cPickle,用c语言编写的,速度比pickle快1000倍。
2,示例:
1importcPickle as p2shoplistfile='shoplist.data'3shoplist=['apple','mango','carrot']4f=file(shoplistfile,'w')5p.dump(shoplist,f)6f.close()7delshoplist8f=file(shoplistfile)9storedlist=p.load(f)10PRintstoredlist
View Code
为了在文件里储存一个对象,首先以写模式打开一个file对象,然后调用储存器模块的dump函数把对象储存到打开的文件中。这个过程称为储存。
使用pickle模块的load函数来取回对象,这个过程叫取储存。
二,异常
1,使用try:
1importsys2m=raw_input('Enter a float:')3n=raw_input('Enter a float:')4try:5printfloat(m)/float(n)6except:7print'除数不能为0!'8sys.exit()
View Code
2,使用raise语句引发异常:
1classshortInput(Exception):2def__init__(self,length,atleast):3Exception.__init__(self)4self.length=length5self.atleast=atleast6try:7s=raw_input('Enter sth-->')8iflen(s)<3:9raiseshortInput(len(s),3)10exceptEOFError:11print'\nWhy did you do an EOF on me?'12exceptshortInput,x:13print'The input was of length %d,was excepting at least %d'%(x.length,x.atleast)14else:15print'No exception was raised!'
View Code
3,使用try…finally:
1importtime2try:3f=file('format.txt')4whileTrue:5line=f.readline()6iflen(line)==0:7
break8time.sleep(2)9printline10finally:11f.close()12print'Cleaning up……closed the file!'
View Code
三,高级内容
1,特殊方法
名称
说明
__init__(self,……)
在新建对象恰好要被返回使用之前被调用。
__del__(self)
恰好在对象要被删除之前调用。
__lt__(self,other)
当使用小于运算符的时候调用。类似地,对所有运算符都有特殊的方法。
__str__(self)
对对象使用print语句或是使用str()的时候调用。
__getitem__(self,key)
使用x[key]索引操作符的时候调用。
__len__(self)
对序列对象使用len函数时调用。
2,lambda表达式
lambda语句用来创建新的函数对象,并且在运行时返回。
1defmake_repeater(n):2returnlambdas:s*n34twice=make_repeater(2)56printtwice('Word')7printtwice(2)8>>> ================================ RESTART ================================9>>>10wordword114
View Code
3,exec和eval语句
exec语句用来执行存储在字符串或文件中的Python语句。
eval语句用来计算存储在字符串中的有效Python表达式。
1>>>exec'''print \'Hello world\''''2Hello world3>>> eval('2*3')46
View Code
4,assert语句:用来声明某个条件是真的。
5,repr函数:用来取得对象的规范字符串表示。反引号也可以完成这个功能。
1>>> i=[]2>>> i.append('item')3>>>i4['item']5>>>repr(i)6"['item']"7>>>
View Code
四,小结
本章主要初步学习了异常处理,关于异常处理的重要性,相信每位码农先生知道其重要性了,作为初学者,慢慢补充吧。