Python enter 与 exit 方法
上下文管理器协议由 __enter__ 和 __exit__ 两个方法组成,实现资源的自动管理。
协议定义
Python
class ContextManager:
def __enter__(self):
# 进入上下文时执行
# 返回值绑定到 as 后的变量
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# 退出上下文时执行
# 返回 True 抑制异常,False 或 None 传播异常
return False
enter 方法
Python
class DatabaseConnection:
def __init__(self, db_name):
self.db_name = db_name
self.connection = None
def __enter__(self):
self.connection = connect(self.db_name)
return self.connection # 返回连接对象
with DatabaseConnection('mydb') as conn:
conn.execute('SELECT * FROM users')
exit 方法参数
Python
def __exit__(self, exc_type, exc_val, exc_tb):
"
exc_type: 异常类型,无异常时为 None
exc_val: 异常实例,无异常时为 None
exc_tb: 异常追踪对象,无异常时为 None
"
pass
完整示例
Python
class FileHandler:
def __init__(self, filename, mode='r'):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
if exc_type:
print(f"发生异常: {exc_type.__name__}: {exc_val}")
return False # 不抑制异常
# 使用
with FileHandler('test.txt', 'w') as f:
f.write('Hello')
异常处理模式
Python
class SafeOperation:
def __enter__(self):
print("开始操作")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
print("操作成功完成")
else:
print(f"操作失败: {exc_val}")
return True # 抑制异常
with SafeOperation():
raise RuntimeError("出错了") # 异常被抑制
print("程序继续运行")
方法调用时机
| 场景 | enter | exit |
|---|---|---|
| 正常执行 | 进入 with 时 | 退出 with 时 |
| 发生异常 | 进入 with 时 | 异常后立即执行 |
| 异常抑制 | 进入 with 时 | 返回 True 后继续 |
要点总结
__enter__在进入 with 块时调用,返回值绑定到 as 变量__exit__在退出 with 块时必定调用,保证资源释放__exit__三个参数用于异常处理- 返回 True 抑制异常,返回 False 或 None 传播异常
- 两个方法共同构成上下文管理器协议
📝 发现内容有误?点击此处直接编辑