上下文管理协议器
#上下文管理器协议
#法1
import contextlib
@contextlib.contextmanager
def file_open(file_name):
print(“file open”)
yield{}
print(“file end”)
with file_open(“body.txt”) as f_opened:
print(“file processing”)
#法2
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(“doing something”)
with Sample() as sample:
sample.do_something()