深入淺析python with語(yǔ)句簡(jiǎn)介
with 語(yǔ)句是從 Python 2.5 開始引入的一種與異常處理相關(guān)的功能(2.5 版本中要通過 from __future__ import with_statement 導(dǎo)入后才可以使用),從 2.6 版本開始缺省可用(參考 What's new in Python 2.6? 中 with 語(yǔ)句相關(guān)部分介紹)。with 語(yǔ)句適用于對(duì)資源進(jìn)行訪問的場(chǎng)合,確保不管使用過程中是否發(fā)生異常都會(huì)執(zhí)行必要的“清理”操作,釋放資源,比如文件使用后自動(dòng)關(guān)閉、線程中鎖的自動(dòng)獲取和釋放等。
術(shù)語(yǔ)
要使用 with 語(yǔ)句,首先要明白上下文管理器這一概念。有了上下文管理器,with 語(yǔ)句才能工作。
在python中讀寫操作資源,最后需要釋放資源??梢允褂胻ry…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")
總結(jié)
以上所述是小編給大家介紹的python with語(yǔ)句簡(jiǎn)介,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
python numpy生成等差數(shù)列、等比數(shù)列的實(shí)例
今天小編就為大家分享一篇python numpy生成等差數(shù)列、等比數(shù)列的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2020-02-02
關(guān)于django 數(shù)據(jù)庫(kù)遷移(migrate)應(yīng)該知道的一些事
今天小編就為大家分享一篇關(guān)于django 數(shù)據(jù)庫(kù)遷移(migrate)應(yīng)該知道的一些事,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2018-05-05
詳細(xì)過程帶你用Python做車牌自動(dòng)識(shí)別系統(tǒng)
這篇文章主要介紹了帶你用Python做車牌自動(dòng)識(shí)別系統(tǒng)的詳細(xì)過程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08
python copy模塊中的函數(shù)實(shí)例用法
在本篇內(nèi)容里小編給大家整理了關(guān)于python copy模塊的基礎(chǔ)知識(shí)點(diǎn)及實(shí)例用法,有需要的朋友們可以跟著學(xué)習(xí)下。2021-09-09

