python中with as用法_python 中关于with...as的用法
python中的with...as類似于try...except......finally...其用法是
with A() as b:
suite
block
其中A是一個類,該類中必須包含兩個函數__enter__(),和__exit__() ?,b為函數__enter__()函數的返回值,當執行with A() as b: 時,首先會創建一個A 的一個臨時對象,
然后調用__enter__()函數,若__enter__()函數執行出現異常直接終止,并將返回值賦值給b,接著執行suite,若suite中存在異常會中斷執行函數__exit__(),
若__exit()__函數返回True,則接著執行block,否者終止,
若不存在異常,執行完suite后,執行函數__exit__(),最后執行block。
類如:
1.
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
(, NameError("name 'e' is not defined",), )
Traceback (most recent call last):
File "E:\python-workplace\t.py", line 10, in
print e
NameError: name 'e' is not defined
因為exit的返回值為false
總結
以上是生活随笔為你收集整理的python中with as用法_python 中关于with...as的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 放大器非线性失真研究装置_高效布里渊光纤
- 下一篇: 启动ipython内核发生错误_ipyt