本篇文章給大家分享的是有關(guān)如何在python中使用with,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。
我們都知道打開文件有兩種方法:
f = open()
with open() as f:
這兩種方法的區(qū)別就是第一種方法需要我們自己關(guān)閉文件;f.close(),而第二種方法不需要我們自己關(guān)閉文件,無(wú)論是否出現(xiàn)異常,with都會(huì)自動(dòng)幫助我們關(guān)閉文件,這是為什么呢?
我們先自定義一個(gè)類,用with來(lái)打開它:
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")
執(zhí)行結(jié)果:
enter called Traceback (most recent call last): hello python exit called exc_type :exc_val :division by zero File "F:/workspaces/python_workspaces/flask_study/with.py", line 25, in a = 1/0 exc_tb : ZeroDivisionError: division by zero Process finished with exit code 1
我們看到,執(zhí)行結(jié)果的輸入順序,分析如下:
當(dāng)我們with Foo() as foo:時(shí),此時(shí)會(huì)執(zhí)行__enter__方法,然后進(jìn)入執(zhí)行體,也就是:
print("hello python") a = 1/0 print("hello end")
以上就是如何在python中使用with,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。