今天小編給大家分享一下Python上下文管理器如何實(shí)現(xiàn)的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

創(chuàng)新互聯(lián)主營(yíng)盈江網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,重慶APP開發(fā),盈江h(huán)5重慶小程序開發(fā)搭建,盈江網(wǎng)站營(yíng)銷推廣歡迎盈江等地區(qū)企業(yè)咨詢
當(dāng)你的代碼邏輯需要用到如下關(guān)鍵字時(shí),可以考慮使用上下文管理器讓你的代碼更加優(yōu)雅:
try: ... finally: ...
接下來介紹實(shí)現(xiàn)上下文管理器的三種方法。
總所周知,open()是默認(rèn)支持上下文管理器的。所以打開一個(gè)txt文件,并向里面寫入內(nèi)容,再關(guān)閉這個(gè)文件的代碼可以這樣寫:
with open("1.txt", "w") as file:
file.write("this is a demo")這是等同于:
file = None
try:
file = open("1.txt", "w")
file.write("this is a demo")
finally:
file.close()要在Python中實(shí)現(xiàn)with語(yǔ)句的使用,就需要借助上下文管理器協(xié)議。也就是需要實(shí)現(xiàn)__enter__和__exit__兩個(gè)魔法方法。
class OpenMyFile(object):
def __init__(self, path):
self.path = path
def __enter__(self):
print("opening the txt")
self.f = open(self.path, "w")
return self
def __exit__(self, *args, **kwargs):
print("closing the txt")
self.f.close()
def write(self, string):
print("writing...")
self.f.write(string)
with OpenMyFile("2.txt") as file:
file.write("this is a demo2")
# 輸出:
opening the txt
writing...
closing the txt同時(shí)能夠看到本地生成了2.txt文件。需要注意的是,__enter__得return實(shí)例對(duì)象,不然會(huì)報(bào)異常:AttributeError: "NoneType" object has no attribute "write"
這是因?yàn)镻ython中的函數(shù)默認(rèn)返回None。
利用contextlib中的contextmanager裝飾器。
from contextlib import contextmanager
@contextmanager
def open_my_file(path):
print("opening the txt")
f = open("3.txt", "w")
yield f
print("closing the txt")
f.close()
with open_my_file("3.txt") as file:
file.write("this is demo3")
# 輸出:
opening the txt
closing the txt在@contextmanager裝飾的函數(shù)中,需要用yield隔開兩個(gè)邏輯語(yǔ)句。這里yield出來的對(duì)象會(huì)被as后面的變量接收。
利用contextlib中的closing()方法。
from contextlib import closing
class OpenMyFile(object):
def __init__(self, path):
print("opening the txt")
self.f = open(path, "w")
def write(self, string):
self.f.write(string)
def close(self):
print("closing the txt")
self.f.close()
with closing(OpenMyFile("4.txt")) as file:
file.write("this is demo4")
# 輸出:
opening the txt
closing the txt與方法1不同。經(jīng)過closing()方法包裝過后,在with語(yǔ)句結(jié)束時(shí),會(huì)強(qiáng)制調(diào)用對(duì)象的close()方法。所以使用方法3時(shí),需要定義的方法不是__exit__()而是close()。
以上就是“Python上下文管理器如何實(shí)現(xiàn)”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享名稱:Python上下文管理器如何實(shí)現(xiàn)
當(dāng)前路徑:http://chinadenli.net/article44/jigphe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、網(wǎng)站設(shè)計(jì)、、全網(wǎng)營(yíng)銷推廣、關(guān)鍵詞優(yōu)化、App設(shè)計(jì)
聲明:本網(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í)需注明來源: 創(chuàng)新互聯(lián)