您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)Python 中with關(guān)鍵字如何使用,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
demo.py(with 打開文件):
# open 方法的返回值賦值給變量 f,當(dāng)離開 with 代碼塊的時(shí)候,系統(tǒng)會(huì)自動(dòng)調(diào)用 f.close() 方法 # with 的作用和使用 try/finally 語句是一樣的。 with open("output.txt", "r") as f: f.write("XXXXX")
demo.py(with,上下文管理器):
# 自定義的MyFile類 # 實(shí)現(xiàn)了 __enter__() 和 __exit__() 方法的對(duì)象都可稱之為上下文管理器 class MyFile(): def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): print("entering") self.f = open(self.filename, self.mode) return self.f # with代碼塊執(zhí)行完或者with中發(fā)生異常,就會(huì)自動(dòng)執(zhí)行__exit__方法。 def __exit__(self, *args): print("will exit") self.f.close() # 會(huì)自動(dòng)調(diào)用MyFile對(duì)象的__enter__方法,并將返回值賦給f變量。 with MyFile('out.txt', 'w') as f: print("writing") f.write('hello, python') # 當(dāng)with代碼塊執(zhí)行結(jié)束,或出現(xiàn)異常時(shí),會(huì)自動(dòng)調(diào)用MyFile對(duì)象的__exit__方法。
demo.py(實(shí)現(xiàn)上下文管理器的另一種方式):
from contextlib import contextmanager @contextmanager def my_open(path, mode): f = open(path, mode) yield f f.close() # 將my_open函數(shù)中yield后的變量值賦給f變量。 with my_open('out.txt', 'w') as f: f.write("XXXXX") # 當(dāng)with代碼塊執(zhí)行結(jié)束,或出現(xiàn)異常時(shí),會(huì)自動(dòng)執(zhí)行yield后的代碼。
看完上述內(nèi)容,你們對(duì)Python 中with關(guān)鍵字如何使用有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。