1 #!/user/bin/env python 2 # -*- coding:utf-8 -*- 3 4 # 上下文管理器协议 5 6 7 class Sample: 8 def __enter__(self): 9 print('enter') 10 return self 11 12 def __exit__(self, exc_type, exc_val, exc_tb): 13 print('exit') 14 15 @staticmethod 16 def do_something(): 17 print('do_something') 18 19 20 with Sample() as sample: 21 sample.do_something()
enter do_something exit