python中的with...as相似於try...except......finally...其用法是python
with A() as b:函數
suiteui
blockspa
其中A是一個類,該類中必須包含兩個函數__enter__(),和__exit__() ,b爲函數__enter__()函數的返回值,當執行with A() as b: 時,首先會建立一個A 的一個臨時對象,code
而後調用__enter__()函數,若__enter__()函數執行出現異常直接終止,並將返回值賦值給b,接着執行suite,若suite中存在異常會中斷執行函數__exit__(),對象
若__exit()__函數返回True,則接着執行block,否者終止,it
若不存在異常,執行完suite後,執行函數__exit__(),最後執行block。io
類如:ast
1.class
class open:
def __enter__(self):
print 'return'
return 2
def __exit__(self,type,value,traceback): #如有異常會將異常的信息賦值給exit的參數type,value,traceback,否者爲None
return isinstance(value,NameError) #若是出現NameError返回true
with open() as s:
print s
print e
print 'hello'
print 'nihao'
執行結果:
return
2
nihao
2.
class open:
def __enter__(self):
print 'return'
return 2
def __exit__(self,*args): #異常的信息以tuple形式賦給args
print args #隱藏了返回值false
with open() as s:
print s
print e
print 'hello'
print 'nihao'
結果:
return
2
(<type 'exceptions.NameError'>, NameError("name 'e' is not defined",), <traceback object at 0x0000000002EE43C8>)
Traceback (most recent call last):
File "E:\python-workplace\t.py", line 10, in <module>
print e
NameError: name 'e' is not defined
由於exit的返回值爲false