Python學(xué)習(xí)系列(九)(IO與異常處理)
Python學(xué)習(xí)系列(八)( 面向?qū)ο蠡A(chǔ))
一,存儲器
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為了在文件里儲存一個對象,首先以寫模式打開一個file對象,然后調(diào)用儲存器模塊的dump函數(shù)把對象儲存到打開的文件中。這個過程稱為儲存。
使用pickle模塊的load函數(shù)來取回對象,這個過程叫取儲存。
二,異常
1,使用try:

1 import sys2 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 '除數(shù)不能為0!'8 sys.exit()2,使用raise語句引發(fā)異常:

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!'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 line10 finally:11 f.close()12 print 'Cleaning up……closed the file!'三,高級內(nèi)容
1,特殊方法
名稱 | 說明 |
| __init__(self,……) | 在新建對象恰好要被返回使用之前被調(diào)用。 |
| __del__(self) | 恰好在對象要被刪除之前調(diào)用。 |
| __lt__(self,other) | 當(dāng)使用小于運算符的時候調(diào)用。類似地,對所有運算符都有特殊的方法。 |
| __str__(self) | 對對象使用print語句或是使用str()的時候調(diào)用。 |
__getitem__(self,key) | 使用x[key]索引操作符的時候調(diào)用。 |
__len__(self) | 對序列對象使用len函數(shù)時調(diào)用。 |
2,lambda表達式
lambda語句用來創(chuàng)建新的函數(shù)對象,并且在運行時返回。

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 wordword11 4
1 >>> exec '''print /'Hello world/''''2 Hello world3 >>> eval('2*3')4 6
1 >>> i=[]2 >>> i.append('item')3 >>> i4 ['item']5 >>> repr(i)6 "['item']"7 >>> 四,小結(jié)
本章主要初步學(xué)習(xí)了異常處理,關(guān)于異常處理的重要性,相信每位碼農(nóng)先生知道其重要性了,作為初學(xué)者,慢慢補充吧。
新聞熱點
疑難解答