当前位置: 首页 > news >正文

Python 中的上下文管理器与 `with` 语句全解析

在 Python 编程中,上下文管理器和 with 语句是确保资源正确管理的重要工具。它们可以帮助我们自动管理资源的分配和释放,避免资源泄漏,使代码更加简洁和安全。今天,就让我们一起深入学习 Python 中的上下文管理器和 with 语句,掌握它们的使用方法和实现原理。

一、上下文管理器(Context Manager)

(一)什么是上下文管理器?

上下文管理器是一个对象,它定义了进入和退出上下文管理器时的行为。上下文管理器通常用于管理资源的分配和释放,如文件、网络连接、锁等。

(二)上下文管理器的协议

上下文管理器需要实现两个方法:

  • __enter__():进入上下文管理器时调用,返回一个资源对象。
  • __exit__():退出上下文管理器时调用,负责清理资源。

(三)示例代码

class MyContextManager:def __enter__(self):print("Entering the context")return selfdef __exit__(self, exc_type, exc_value, traceback):print("Exiting the context")if exc_type:print(f"An exception occurred: {exc_value}")return False  # 返回 False 表示不处理异常 [555dianying](https://zhuanlan.zhihu.com/p/1956329570794991729)# 使用上下文管理器
with MyContextManager():print("Inside the context")

输出

Entering the context
Inside the context
Exiting the context

二、with 语句

(一)with 语句的基本用法

with 语句用于创建一个上下文管理器,确保资源在使用后正确释放。with 语句的语法如下 :

with context_manager as resource:# 使用资源

(二)文件操作示例

with open('example.txt', 'r') as file:content = file.read()print(content)

在这个例子中,open() 函数返回一个文件对象,它是一个上下文管理器。with 语句确保文件在使用后正确关闭,即使发生异常也会自动关闭文件。盘搜

(三)锁操作示例

import threadinglock = threading.Lock()with lock:print("Inside the lock")

在这个例子中,threading.Lock 是一个上下文管理器,with 语句确保锁在使用后正确释放。

三、上下文管理器的高级用法

(一)使用 contextlib 模块

Python 提供了一个 contextlib 模块,它包含了一些工具,可以帮助我们更方便地创建上下文管理器。吴签cili

1. 使用 contextlib.contextmanager

contextlib.contextmanager 是一个装饰器,用于创建上下文管理器。

from contextlib import contextmanager@contextmanager
def my_context_manager():print("Entering the context")yieldprint("Exiting the context")# 使用上下文管理器
with my_context_manager():print("Inside the context")

输出

Entering the context
Inside the context
Exiting the context

2. 使用 contextlib.closing

contextlib.closing 是一个上下文管理器,用于确保对象的 close() 方法在退出时被调用。

from contextlib import closingwith closing(open('example.txt', 'r')) as file:content = file.read()print(content)

(二)自定义上下文管理器

可以通过实现 __enter__()__exit__() 方法来创建自定义上下文管理器。

示例代码

class MyContextManager:def __enter__(self):print("Entering the context")return selfdef __exit__(self, exc_type, exc_value, traceback):print("Exiting the context")if exc_type:print(f"An exception occurred: {exc_value}")return False  # 返回 False 表示不处理异常# 使用上下文管理器
with MyContextManager():print("Inside the context")

输出

Entering the context
Inside the context
Exiting the context

四、with 语句的异常处理

(一)异常处理

__exit__() 方法可以捕获和处理异常。如果返回 True,表示异常已被处理,不会向外抛出;如果返回 False,异常会向外抛出。DataTool

示例代码

class MyContextManager:def __enter__(self):print("Entering the context")return selfdef __exit__(self, exc_type, exc_value, traceback):print("Exiting the context")if exc_type:print(f"An exception occurred: {exc_value}")return True  # 返回 True 表示处理异常# 使用上下文管理器
with MyContextManager():print("Inside the context")raise ValueError("An error occurred")

输出

Entering the context
Inside the context
Exiting the context
An exception occurred: An error occurred

(二)嵌套 with 语句

可以嵌套使用 with 语句,管理多个资源。

示例代码

with open('example1.txt', 'r') as file1, open('example2.txt', 'r') as file2:content1 = file1.read()content2 = file2.read()print(content1)print(content2)

五、总结

通过本文的介绍,你已经全面掌握了 Python 中的上下文管理器和 with 语句,从基础概念到高级用法。以下是关键点总结:

  • 上下文管理器:实现了 __enter__()__exit__() 方法的对象,用于管理资源的分配和释放。
  • with 语句:用于创建上下文管理器,确保资源在使用后正确释放。
  • 高级用法:使用 contextlib 模块简化上下文管理器的创建,自定义上下文管理器,异常处理,嵌套 with 语句。
http://www.hskmm.com/?act=detail&tid=21401

相关文章:

  • 用友U8Api 接口对接
  • 填坑:VC++ 采用OpenSSL 3.0接口方式生成RSA密钥 - 教程
  • JUC:AQS
  • CF1980F2 Field Division (hard version) 题解
  • JUC:ThreadLocal
  • 广义串并联图とP6790 [SNOI2020] 生成树
  • JUC: Java对象内存布局和对象头
  • Manim实现波浪形文字特效
  • JUC: synchronized与锁升级
  • lang / philipino / feilvbin / taglog / tajialu
  • Windows上安装2个不同版本的MySQL5.7和8.4
  • cron表达式,每月1号凌晨3点执行和每周4凌晨3点半执行
  • 2025.9.30
  • C#/.NET/.NET Core技术前沿周刊 | 第 56 期(2025年9.22-9.28)
  • 反转链表
  • 天津港口海鲜之旅全攻略(2025最新版)
  • tomcat创建bat启动,结合任务计划实现自动重启tomcat服务 - 详解
  • 实用指南:【论文精读】Few-Shot Object Detection with Attention-RPN and Multi-Relation Detector
  • Chromium V8类型混淆漏洞CVE-2025-10585安全分析
  • Claude 4.5 刚刚发布,能连肝 30 多个小时,史上最卷 AI 诞生
  • 香橙派5pro驱动开发(一)
  • Python 脚本遇到 SSL 证书问题
  • sa-token开发时遇到的问题
  • HR如何摆脱入离职事务性内耗?组织管理系统助力聚焦人才价值挖掘
  • 基于SpringAI构建大模型应用
  • C# TCP - 串口转发 - 实践
  • 【研发规范】Git 提交(commit)、CodeReview规范
  • PCIE 各个管脚的作用是什么?
  • Windows 11 局域网打印机共享设置
  • DailyPaper-2025-9-29