簡介
python中,with-as
語法一般用于資源關閉的情況,可以當成try - except - finally
的一種優(yōu)雅寫法,不需要我們自己頻繁編寫關于釋放資源的代碼。
以打開文件資源為例,通常的寫法:
try:
f = open("xxx")
except:
print("except when open file")
exit(0)
try:
do ...
except:
do ...
finally:
f.close()
(PS:python中,try
,if
語塊等并沒有類似于其他語言中的作用域概念)
但是,用with ... as ...
寫法,可以變成這樣:
with open("xxx") as f:
do ...
原理
with-as
表達式語法需要python中class
的支持:
class TEST:
def __enter__ (self):
do ...
return somethings
def __exit__ (self, type, value, traceback):
do ... (finally)
當執(zhí)行with-as
時(with TEST() as t
),首先調用__enter__
函數,
然后把該函數的return值返回給as
后面指定的變量。之后執(zhí)行執(zhí)行正常代碼塊,
最終,流程正常完畢或有異常狀況,都會執(zhí)行__exit__
函數。
后記
總之,with-as
是python在語言級別上實現了一種try-except-finally
的語法糖