class Sample: # 上下文管理器协议
def __enter__(self):
print("enter")
# 获取资源
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# 释放资源
print("exit")
def do_something(self):
print("111")
with Sample() as sample:
sample.do_something()
# output
# enter
# 111
# exit
import contextlib
@contextlib.contextmanager # 用装饰器把函数变为上下文管理器
def file_open(file_name):
print("file open")
yield {}
print("file end")
with file_open("wlq.txt") as f:
print("file processing!")
# output
# file open
# file processing!
# file end