我們都知道打開文件有兩種方法:
f = open() with open() as f:這兩種方法的區別就是第一種方法需要我們自己關閉文件;f.close(),而第二種方法不需要我們自己關閉文件,無論是否出現異常,with都會自動幫助我們關閉文件,這是為什么呢?
我們先自定義一個類,用with來打開它:
class Foo(): def __enter__(self): print("enter called") def __exit__(self, exc_type, exc_val, exc_tb): print("exit called") print("exc_type :%s"%exc_type) print("exc_val :%s"%exc_val) print("exc_tb :%s"%exc_tb)with Foo() as foo: print("hello python") a = 1/0 print("hello end")
執行結果:
enter calledTraceback (most recent call last):hello pythonexit calledexc_type :<class 'ZeroDivisionError'>exc_val :division by zero File "F:/workspaces/python_workspaces/flask_study/with.py", line 25, in <module> a = 1/0exc_tb :<traceback object at 0x0000023C4EDBB9C8>ZeroDivisionError: division by zeroProcess finished with exit code 1
我們看到,執行結果的輸入順序,分析如下:
當我們with Foo() as foo:時,此時會執行__enter__方法,然后進入執行體,也就是:
print("hello python")a = 1/0print("hello end")
語句,但是在a=1/0出現了異常,with將會中止,此時就執行__exit__方法,就算不出現異常,當執行體被執行完畢之后,__exit__方法仍然被執行一次。
我們回到with open("file")as f: 不用關閉文件的原因就是在__exit__方法中,存在關閉文件的操作,所以不用我們手工關閉文件,with已將為我們做好了這個操作,這就可以理解了。
以上就是小編整理的相關內容,如果大家有任何補充可以聯系武林站長站小編。
新聞熱點
疑難解答