with 語句是從 Python 2.5 開始引入的一種與異常處理相關的功能(2.5 版本中要通過 from __future__ import with_statement 導入后才可以使用),從 2.6 版本開始缺省可用(參考 What's new in Python 2.6? 中 with 語句相關部分介紹)。with 語句適用于對資源進行訪問的場合,確保不管使用過程中是否發(fā)生異常都會執(zhí)行必要的“清理”操作,釋放資源,比如文件使用后自動關閉、線程中鎖的自動獲取和釋放等。
術語
要使用 with 語句,首先要明白上下文管理器這一概念。有了上下文管理器,with 語句才能工作。
在python中讀寫操作資源,最后需要釋放資源。可以使用try…finally結構實現(xiàn)資源的正確釋放,python提供了一個with語句能更簡便的實現(xiàn)釋放資源。
1. python像文件的操作open等已經(jīng)可以直接使用with語句
2. 可以自定義一個支持with語句對象
3. 使用contextlib也可以使用with語句對象
4. 針對需要close操作的對象with的使用
示例代碼中有4種使用標注
# 自定義支持with語句的對象 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語句對象 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語句 (自動關閉文件) with open("test.txt", "w") as f: f.write("write test") # 2. 自動定義with語句 with DummyRes("test") as res: print("With body 1") raise Exception print("With body 2") # 3. 利用contextlib定義with語句 with demo(): print("exc demo") # 4. closing 上下文 (適合有close操作的情況) with Closing(ClosingDemo()): print("Use Resoures")
分享文章:深入淺析pythonwith語句簡介-創(chuàng)新互聯(lián)
URL地址:http://www.chinadenli.net/article44/dcsjee.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供移動網(wǎng)站建設、云服務器、品牌網(wǎng)站建設、網(wǎng)站排名、自適應網(wǎng)站、微信公眾號
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容