Python学习系列(九)(IO与异常处理)

Python学习系列(九)(IO与异常处理)

Python学习系列(八)( 面向对象基础)

一,存储器

1,Python提供一个标准的模块,称为pickle,使用它既可以在一个文件中存储任何Python对象,又可以把它完整的取出来,这被称为持久的存储对象。类似的,还有一个功能与之相同的模块—cPickle,用c语言编写的,速度比pickle快1000倍。

2,示例:

 1 import cPickle as p  2 shoplistfile='shoplist.data'

 3 shoplist=['apple','mango','carrot']  4 f=file(shoplistfile,'w')  5 p.dump(shoplist,f)  6 f.close()  7 del shoplist  8 f=file(shoplistfile)  9 storedlist=p.load(f) 10 print storedlist
View Code

为了在文件里储存一个对象,首先以写模式打开一个file对象,然后调用储存器模块的dump函数把对象储存到打开的文件中。这个过程称为储存。

使用pickle模块的load函数来取回对象,这个过程叫取储存

二,异常 

1,使用try

1 import sys 2 m=raw_input('Enter a float:') 3 n=raw_input('Enter a float:') 4 try: 5     print float(m)/float(n) 6 except: 7     print '除数不能为0!'

8     sys.exit()
View Code

2,使用raise语句引发异常:

 1 class shortInput(Exception):  2     def __init__(self,length,atleast):  3         Exception.__init__(self)  4         self.length=length  5         self.atleast=atleast  6 try:  7     s=raw_input('Enter sth-->')  8     if len(s)<3:  9         raise shortInput(len(s),3) 10 except EOFError: 11     print '\nWhy did you do an EOF on me?'

12 except shortInput,x: 13     print 'The input was of length %d,was excepting at least %d'%(x.length,x.atleast) 14 else: 15     print 'No exception was raised!'
View Code

3,使用try…finally

 1 import time  2 try:  3     f=file('format.txt')  4     while True:  5         line=f.readline()  6         if len(line)==0:  7             break

 8         time.sleep(2)  9         print line 10 finally: 11  f.close() 12     print '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语句用来创建新的函数对象,并且在运行时返回。

 1 def make_repeater(n):  2     return lambda s:s*n  3  

 4 twice=make_repeater(2)  5  

 6 print twice('word')  7 print twice(2)  8 >>> ================================ RESTART ================================

 9 >>>

10 wordword 11 4
View Code
3,execeval语句
    exec语句用来执行存储在字符串或文件中的Python语句。
    eval语句用来计算存储在字符串中的有效Python表达式。
1 >>> exec '''print \'Hello world\''''

2 Hello world 3 >>> eval('2*3') 4 6
View Code
4,assert语句:用来声明某个条件是真的。
5,repr函数:用来取得对象的规范字符串表示。反引号也可以完成这个功能。
1 >>> i=[] 2 >>> i.append('item') 3 >>> i 4 ['item'] 5 >>> repr(i) 6 "['item']"

7 >>> 
View Code

四,小结

   本章主要初步学习了异常处理,关于异常处理的重要性,相信每位码农先生知道其重要性了,作为初学者,慢慢补充吧。

 

你可能感兴趣的:(python)