濮阳杆衣贸易有限公司

主頁 > 知識庫 > Python上下文管理器實現(xiàn)方法總結(jié)

Python上下文管理器實現(xiàn)方法總結(jié)

熱門標簽:如何地圖標注公司 外賣地址有什么地圖標注 長春極信防封電銷卡批發(fā) 銀川電話機器人電話 煙臺電話外呼營銷系統(tǒng) 電銷機器人錄音要學(xué)習什么 企業(yè)彩鈴地圖標注 上海正規(guī)的外呼系統(tǒng)最新報價 預(yù)覽式外呼系統(tǒng)

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

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

try:
	...
finally:
	...

接下來介紹實現(xiàn)上下文管理器的三種方法。

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

總所周知,open()是默認支持上下文管理器的。所以打開一個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中實現(xiàn)with語句的使用,就需要借助上下文管理器協(xié)議。也就是需要實現(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實例對象,不然會報異常:AttributeError: 'NoneType' object has no attribute 'write'

這是因為Python中的函數(shù)默認返回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é)束時,會強制調(diào)用對象的close()方法。所以使用方法3時,需要定義的方法不是__exit__()而是close()。

到此這篇關(guān)于Python上下文管理器實現(xiàn)方法總結(jié)的文章就介紹到這了,更多相關(guān)Python上下文管理器實現(xiàn)的三種方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • Python上下文管理器Content Manager
  • python上下文管理器異常問題解決方法
  • 詳解python with 上下文管理器
  • Python實現(xiàn)上下文管理器的方法
  • python中with語句結(jié)合上下文管理器操作詳解
  • Python上下文管理器類和上下文管理器裝飾器contextmanager用法實例分析

標簽:盤錦 佳木斯 宜昌 珠海 上饒 湖北 西寧 潮州

巨人網(wǎng)絡(luò)通訊聲明:本文標題《Python上下文管理器實現(xiàn)方法總結(jié)》,本文關(guān)鍵詞  Python,上下文,管理器,實現(xiàn),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Python上下文管理器實現(xiàn)方法總結(jié)》相關(guān)的同類信息!
  • 本頁收集關(guān)于Python上下文管理器實現(xiàn)方法總結(jié)的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    西宁市| 稻城县| 黔西县| 通许县| 沙雅县| 始兴县| 抚松县| 格尔木市| 镶黄旗| 理塘县| 怀远县| 鹤峰县| 嘉善县| 额济纳旗| 伊吾县| 嘉鱼县| 辛集市| 信宜市| 清涧县| 固安县| 广丰县| 浦县| 霍城县| 正安县| 仪陇县| 当雄县| 浦城县| 桑日县| 朔州市| 崇阳县| 罗江县| 灵寿县| 河南省| 玉溪市| 东丰县| 平凉市| 尉氏县| 山东| 铜山县| 石泉县| 林甸县|