溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python上下文管理器實現方法有哪些

發布時間:2021-07-19 16:45:47 來源:億速云 閱讀:193 作者:chen 欄目:開發技術

這篇文章主要介紹“Python上下文管理器實現方法有哪些”,在日常操作中,相信很多人在Python上下文管理器實現方法有哪些問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Python上下文管理器實現方法有哪些”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

目錄
  • 什么時候可以考慮上下文管理器

  • 方法1(上下文管理器協議)

  • 方法2(@contextmanager)

  • 方法3(contextlib.closing())

什么時候可以考慮上下文管理器

當你的代碼邏輯需要用到如下關鍵字時,可以考慮使用上下文管理器讓你的代碼更加優雅:

try:
	...
finally:
	...

接下來介紹實現上下文管理器的三種方法。

方法1(上下文管理器協議)

總所周知,open()是默認支持上下文管理器的。所以打開一個txt文件,并向里面寫入內容,再關閉這個文件的代碼可以這樣寫:

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中實現with語句的使用,就需要借助上下文管理器協議。也就是需要實現__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實例對象,不然會報異常:AttributeError: 'NoneType' object has no attribute 'write'

這是因為Python中的函數默認返回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裝飾的函數中,需要用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不同。經過closing()方法包裝過后,在with語句結束時,會強制調用對象的close()方法。所以使用方法3時,需要定義的方法不是__exit__()而是close()。

到此,關于“Python上下文管理器實現方法有哪些”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女