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

Python with 语句原理

with 语句简化了资源管理,确保资源在使用后自动释放,无论是否发生异常。

执行流程

Python
with open('file.txt') as f:
    content = f.read()

# 等价于
f = open('file.txt')
try:
    content = f.read()
finally:
    f.close()

执行顺序

Python
1. 执行 __enter__ 方法,获取资源
2. 将 __enter__ 返回值赋给 as 后的变量
3. 执行 with 代码块
4. 无论是否异常,执行 __exit__ 方法释放资源

基本使用

Python
# 文件操作
with open('data.txt', 'w') as f:
    f.write('Hello')

# 多个上下文管理器
with open('input.txt') as fin, open('output.txt', 'w') as fout:
    fout.write(fin.read())

# 锁资源
import threading
lock = threading.Lock()
with lock:
    # 临界区代码
    pass

自定义上下文管理器

Python
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time.time()
        print(f"耗时: {self.end - self.start:.2f}秒")
        return False  # 不抑制异常

with Timer() as t:
    # 执行耗时操作
    sum(range(1000000))

exit 返回值

返回值行为
False异常正常传播
True抑制异常,继续执行
text
class SuppressError:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"捕获异常: {exc_type}")
        return True  # 抑制异常

with SuppressError():
    raise ValueError("被抑制的异常")
print("继续执行")  # 正常执行

要点总结

  • with 语句自动调用 __enter____exit__ 方法
  • __enter__ 返回值绑定到 as 变量
  • __exit__ 始终执行,确保资源释放
  • __exit__ 返回 True 可抑制异常
  • 适用于文件、锁、数据库连接等资源管理

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

← 上一篇 Python contextlib 模块
下一篇 → Python 嵌套上下文管理器
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

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

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