什么是python上下文管理器
类似 with open
的实现
上下文管理器需要实现上下文管理协议,那什么是上下文管理协议呢。
上下文管理协议:实现了__enter__
和__exit__
方法。(一如迭代器协议是实现__iter__
方法)
例:
class Contextor:
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
contextor = Contextor()
with contextor [as var]:
with_body
with语句开始执行的时候自动调用__enter__方法,当with语句结束或者遇到异常的时候自动调用__exit__