定義:上下文管理協議,即with語句,爲了讓一個對象兼容with語句,必須在這個對象的類中聲明__enter__
和__exit__
方法python
示例一:code
class MyResource: def __enter__(self): print("connected") return self def __exit__(self, *args, **kwargs): print("close") # 遇到異常須要關閉的時候 裏面返回True # 外層就再也不拋異常 否者拋異常 return True def query(self): print("query data") try: with MyResource() as obj_A: # 這裏面的obj_A 就是__enter__方法return self 實例化的對象 obj_A.query() except Exception as e: print(e) """ 打印結果: connected query data close """
示例二:對象
class MyResource: def __enter__(self): print("connected") return self def __exit__(self, *args, **kwargs): print("close") # 遇到異常須要關閉的時候 裏面返回True # 外層就再也不拋異常 否者拋異常 return True def query(self): print("query data") try: with MyResource() as obj_A: 1 / 0 # 這個位置就直接退出 obj_A.query() except Exception as e: print(e) """ 打印結果: connected close """
contextmanager 實現上下文管理協議it
class MyResource: def query(self): print("query data") from contextlib import contextmanager @contextmanager def make_myresource(): print("connected") yield MyResource() # 這裏面將實例化的MyResource()給r print("close") with make_myresource() as r: r.query() """ result: connected query data close """
且將生活一飲而盡之上下文管理io
from contextlib import contextmanager @contextmanager def book_mark(): print("<<", end='') yield print('>>', end='') with book_mark(): print("且將生活一飲而盡", end='') """ <<且將生活一飲而盡>> """
且將生活一飲而盡之裝飾器class
def outer(f): def inner(*args, **kwargs): print("<<", end="") f(*args, **kwargs) print(">>", end="") return inner @outer def println(str): print(str, end="") println("且將生活一飲而盡") """ <<且將生活一飲而盡>> """