###上下文管理器
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-09-11 18:01:31 发布
本文展示了如何使用Python的上下文管理器(如`with`语句)来优雅地获取和释放资源,例如在`Sample`类中实现的`__enter__`和`__exit__`方法。同时,还介绍了`contextlib`模块中的`contextmanager`装饰器,用于简化自定义上下文管理器的创建,如`file_open`函数的实现。通过这两个例子,读者可以更好地理解和应用Python中的资源管理机制。
摘要由CSDN通过智能技术生成