遵循上下文管理器协议的类可以使用with来进行处理
class WithClass:
def __enter__(self):
print("进入了...")
def __exit__(self,exc_type,exc_val,_exc_tb):
print("退出了...")
def do_something(self):
print("处理了...")
with WithClass() as with_instance:
with_instance.do_something()
'''
输出的结果是:
进入了...
处理了...
退出了...
'''
满足上下文管理协议,需要有 __enter__,__exit__两个函数
通过with进行实例化对象,能够自动调用enter和exit
使用contextlib
import contextlib
@contextlib.contextmanager
def file_open(file_name):
print("进来了")
yield {}
print("退出了")
with file_open("文件名.txt") as f:
print("使用了")
使用contextlib实现上下文管理
该装饰器的作用就是把该函数改造成为满足上下文管理器协议的一个函数
yield 上面的代码实际上就是 __enter__函数的功能
yield 下面的代码实际上就是 __exit__函数的功能