with 語(yǔ)句是從 Python 2.5 開(kāi)始引入的一種與異常處理相關(guān)的功能(2.5 版本中要通過(guò) from __future__ import with_statement 導(dǎo)入后才可以使用),從 2.6 版本開(kāi)始缺省可用(參考 What's new in Python 2.6? 中 with 語(yǔ)句相關(guān)部分介紹)。with 語(yǔ)句適用于對(duì)資源進(jìn)行訪問(wèn)的場(chǎng)合,確保不管使用過(guò)程中是否發(fā)生異常都會(huì)執(zhí)行必要的“清理”操作,釋放資源,比如文件使用后自動(dòng)關(guān)閉、線程中鎖的自動(dòng)獲取和釋放等。
術(shù)語(yǔ)
要使用 with 語(yǔ)句,首先要明白上下文管理器這一概念。有了上下文管理器,with 語(yǔ)句才能工作。
在python中讀寫(xiě)操作資源,最后需要釋放資源。可以使用try…finally結(jié)構(gòu)實(shí)現(xiàn)資源的正確釋放,python提供了一個(gè)with語(yǔ)句能更簡(jiǎn)便的實(shí)現(xiàn)釋放資源。
1. python像文件的操作open等已經(jīng)可以直接使用with語(yǔ)句
2. 可以自定義一個(gè)支持with語(yǔ)句對(duì)象
3. 使用contextlib也可以使用with語(yǔ)句對(duì)象
4. 針對(duì)需要close操作的對(duì)象with的使用
示例代碼中有4種使用標(biāo)注
# 自定義支持with語(yǔ)句的對(duì)象 class DummyRes: def __init__(self, tag): self.tag = tag def __enter__(self): print("Enter >>> {}".format(self.tag)) return self def __exit__(self, exc_type, exc_value, exc_tb): print("Exit <<< {}".format(self.tag)) if exc_tb is None: print("Exit without Exception {}".format(self.tag)) return False else: print("Exit with Exception {}".format(self.tag)) return True # 支持closing 上下文with語(yǔ)句對(duì)象 class Closing: def __init__(self, thing): self.thing = thing def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_tb): self.thing.close() class ClosingDemo: def __init__(self): self.acquire() def acquire(self): print("Acquire RES") def close(self): print("Close RES") from contextlib import contextmanager class ContextDemo: def __init__(self): print("Context Demo init") raise Exception print("Context Demo init") def print(self): print("Context Demo print 1") #raise Exception print("Context Demo print 2") def close(self): print("Context Demo close") def context_demo(): print("context demo in") raise Exception print("context demo out") @contextmanager def demo(): print("Allocate Resoures") try: yield context_demo finally: print("raise exception") #yield "*** contextmanager demo ***" print("Free Resoures") if __name__ == "__main__": # 1. 使用with語(yǔ)句 (自動(dòng)關(guān)閉文件) with open("test.txt", "w") as f: f.write("write test") # 2. 自動(dòng)定義with語(yǔ)句 with DummyRes("test") as res: print("With body 1") raise Exception print("With body 2") # 3. 利用contextlib定義with語(yǔ)句 with demo(): print("exc demo") # 4. closing 上下文 (適合有close操作的情況) with Closing(ClosingDemo()): print("Use Resoures")
分享文章:深入淺析pythonwith語(yǔ)句簡(jiǎn)介-創(chuàng)新互聯(lián)
URL地址:http://m.newbst.com/article44/dcsjee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供移動(dòng)網(wǎng)站建設(shè)、云服務(wù)器、品牌網(wǎng)站建設(shè)、網(wǎng)站排名、自適應(yīng)網(wǎng)站、微信公眾號(hào)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容