簡介
python中嘱支,with-as
語法一般用于資源關(guān)閉的情況,可以當(dāng)成try - except - finally
的一種優(yōu)雅寫法,不需要我們自己頻繁編寫關(guān)于釋放資源的代碼零抬。
以打開文件資源為例,通常的寫法:
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)
當(dāng)執(zhí)行with-as
時(with TEST() as t
)忽妒,首先調(diào)用__enter__
函數(shù),
然后把該函數(shù)的return值返回給as
后面指定的變量兼贸。之后執(zhí)行執(zhí)行正常代碼塊段直,
最終,流程正常完畢或有異常狀況溶诞,都會執(zhí)行__exit__
函數(shù)鸯檬。
后記
總之,with-as
是python在語言級別上實現(xiàn)了一種try-except-finally
的語法糖