Python上下文管理器實(shí)現(xiàn)方法總結(jié)
什么時候可以考慮上下文管理器
當(dāng)你的代碼邏輯需要用到如下關(guān)鍵字時,可以考慮使用上下文管理器讓你的代碼更加優(yōu)雅:
try: ... finally: ...
接下來介紹實(shí)現(xiàn)上下文管理器的三種方法。
方法1(上下文管理器協(xié)議)
總所周知,open()是默認(rèn)支持上下文管理器的。所以打開一個txt文件,并向里面寫入內(nèi)容,再關(guān)閉這個文件的代碼可以這樣寫:
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語句的使用,就需要借助上下文管理器協(xié)議。也就是需要實(shí)現(xiàn)__enter__和__exit__兩個魔法方法。
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
同時能夠看到本地生成了2.txt文件。需要注意的是,__enter__得return實(shí)例對象,不然會報異常:AttributeError: 'NoneType' object has no attribute 'write'
這是因?yàn)镻ython中的函數(shù)默認(rèn)返回None。
方法2(@contextmanager)
利用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隔開兩個邏輯語句。這里yield出來的對象會被as后面的變量接收。
方法3(contextlib.closing())
利用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語句結(jié)束時,會強(qiáng)制調(diào)用對象的close()方法。所以使用方法3時,需要定義的方法不是__exit__()而是close()。
到此這篇關(guān)于Python上下文管理器實(shí)現(xiàn)方法總結(jié)的文章就介紹到這了,更多相關(guān)Python上下文管理器實(shí)現(xiàn)的三種方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python使用windows設(shè)置定時執(zhí)行腳本
這篇文章主要介紹了Python使用windows設(shè)置定時執(zhí)行腳本,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11解決Django響應(yīng)JsonResponse返回json格式數(shù)據(jù)報錯問題
這篇文章主要介紹了解決Django響應(yīng)JsonResponse返回json格式數(shù)據(jù)報錯問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08Python實(shí)現(xiàn)使用dir獲取類的方法列表
今天小編就為大家分享一篇Python實(shí)現(xiàn)使用dir獲取類的方法列表,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12