全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-19 8 分钟 ✍️ juanwangdev

Python enterexit 方法

上下文管理器协议由 __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("程序继续运行")

方法调用时机

场景enterexit
正常执行进入 with 时退出 with 时
发生异常进入 with 时异常后立即执行
异常抑制进入 with 时返回 True 后继续

要点总结

  • __enter__ 在进入 with 块时调用,返回值绑定到 as 变量
  • __exit__ 在退出 with 块时必定调用,保证资源释放
  • __exit__ 三个参数用于异常处理
  • 返回 True 抑制异常,返回 False 或 None 传播异常
  • 两个方法共同构成上下文管理器协议

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python 装饰器堆叠
下一篇 → Python __exit__ 异常处理
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库