聚焦 Python 编程中的高效工具与高级技巧,提升代码质量与开发效率。
21. 上下文管理器与 with
语句进阶
自定义上下文管理器(类实现)
class DatabaseConnection:
def __enter__(self):
print("建立数据库连接")
return self # 返回资源对象
def __exit__(self, exc_type, exc_val, exc_tb):
print("关闭数据库连接")
with DatabaseConnection() as conn:
print("执行数据库操作")
使用 contextlib
简化实现
from contextlib import contextmanager
@contextmanager
def file_manager(filename, mode):
file = open(filename, mode)
try:
yield file # 返回资源
finally:
file.close()
with file_manager(