上下文管理协议
-
定义:上下文管理协议,即with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明
__enter__
和__exit__
方法 -
示例一:
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 实现上下文管理协议
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 """
-
且将生活一饮而尽之上下文管理
from contextlib import contextmanager @contextmanager def book_mark(): print("<<", end='') yield print('>>', end='') with book_mark(): print("且将生活一饮而尽", end='') """ <<且将生活一饮而尽>> """
-
且将生活一饮而尽之装饰器
def outer(f): def inner(*args, **kwargs): print("<<", end="") f(*args, **kwargs) print(">>", end="") return inner @outer def println(str): print(str, end="") println("且将生活一饮而尽") """ <<且将生活一饮而尽>> """