Python的上下文管理器

2021-07-13 16:53:43 字數 792 閱讀 3618

class filemag():

def __init__(self,filename):

self.filename=filename

self.f=none

def __enter__(self):

self.f=open(self.filename,encoding="utf-8")

return  self.f

def __exit__(self, exc_type, exc_val, exc_tb):

if self.f:

self.f.close()

if __name__=="__main__":

with filemag("a10_4.py") as book:

for i in book.readlines():

print(i)

定義乙個管理檔案資源物件的上下文管理器類,在進入時開啟檔案,退出時關閉檔案,然後用with語句來使用這個上下文管理器,開啟乙個指定的檔案,並輸出其中的內容。

在每次使用時都不用重新開啟和關閉檔案。

其中在python中實現上下文管理器的模組中還有

import contextlib

@contextlib.contextmanager

def ga(s,e):

print(s)

print(s+" "+e)

print(e)

if __name__=="__main__":

with ga("start","end") as val:

print(val)

python 上下文管理器

上下文管理器允許你在有需要的時候,精確地分配和釋放資源。使用上下文管理器最廣泛的案例就是with語句了。想象下你有兩個需要結對執行的相關操作,然後還要在它們中間放置一段 上下文管理器就是專門讓你做這種事情的。舉個例子 with open some file w as opened file open...

python上下文管理器

上下文管理器是乙個包裝任意 塊的物件。上下文管理器保證進入上下文管理器時,每次 執行的一致性 當退出上下文管理器時,相關資源會被正確 這裡被正確 指的是在 exit 方法自定義 比如關閉資料庫游標 值得注意的是,上下文管理器一定能夠保證退出步驟的執行。如果進入上下文管理器,根據定義,一定會有退出步驟...

Python 上下文管理器

python中的上下文管理器是乙個包裝任意 塊的物件。它在處理資源的開啟關閉 異常的處理等方面有很好的實現方法。1.上下文管理器的語法 假設我們需要讀取乙個檔案中的資料,如下 try test file open test.txt r contents test file.read finally ...