###上下文管理器
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('do something ')
with Sample() as s:
s.do_something()
'''***********'''
import contextlib
@contextlib.contextmanager
def file_open(file_name):
print('file open')
yield {}
print('file end')
with file_open('bobby') as fp:
print('file processing')
Python 上下文管理器
最新推荐文章于 2024-05-30 18:05:01 发布