如果你知道什麼上下文管理器然後你就不需要更多的瞭解__enter__
和__exit__
神奇的方法。讓我們看一個非常簡單的例子。
在這個例子中,我打開myfile.txt的與開放功能的幫助。 盡力/終於塊確保即使發生意外異常myfile.txt將被關閉。
fp=open(r"C:\Users\SharpEl\Desktop\myfile.txt")
try:
for line in fp:
print(line)
finally:
fp.close()
現在我打開相同的文件與與聲明:
with open(r"C:\Users\SharpEl\Desktop\myfile.txt") as fp:
for line in fp:
print(line)
如果你在看代碼,我沒有關閉文件&沒有的try /終於塊。由於與聲明自動關閉myfile.txt。你甚至可以通過調用print(fp.closed)
屬性來檢查它 - 返回True
。
這是因爲開放函數返回的文件對象(在我的例子FP)有兩個內置方法__enter__
和__exit__
。它也被稱爲上下文管理器。 __enter__
方法在與塊的起始處被調用,__exit__
方法在最後被調用。注意:與聲明僅適用於支持上下文管理協議的對象,即他們有__enter__
和__exit__
方法。實現這兩種方法的類被稱爲上下文管理器類。
現在讓我們定義我們自己的上下文管理器類。
class Log:
def __init__(self,filename):
self.filename=filename
self.fp=None
def logging(self,text):
self.fp.write(text+'\n')
def __enter__(self):
print("__enter__")
self.fp=open(self.filename,"a+")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("__exit__")
self.fp.close()
with Log(r"C:\Users\SharpEl\Desktop\myfile.txt") as logfile:
print("Main")
logfile.logging("Test1")
logfile.logging("Test2")
我希望現在你有兩個__enter__
和__exit__
魔術方法基本的瞭解。
這裏一個很好的解釋:http://effbot.org/ zone/python-with-statement.htm – Manur 2012-08-13 09:29:54
@StevenVascellaro編輯問題的代碼通常是一個糟糕的主意,**尤其是當代碼中存在錯誤時。這個問題在Py2中被提出,並且沒有理由將它更新到Py3。 – jpaugh 2018-02-05 19:22:10