学习之上下文管理器

python 复制代码
one_file = open('demo.txt', 'w')
one_file.write("xxxxx")
# raise ValueError  # 如果抛出异常将会报错
one_file.close()
python 复制代码
with open('demo.txt', 'w') as f:  # open--返回的是IO--IO中实现了__enter__方法和__exit__方法
    f.write("aaaa")
python 复制代码
class MyContextManger:
    def __init__(self, filename, mode, encoding='utf-8'):
        self.filename, self.mode, self.encoding = filename, mode, encoding

    def __enter__(self):
        self.file_obj = open(self.filename, mode=self.mode, encoding=self.encoding)
        return self.file_obj

    def __exit__(self, exc_type, exc_val, exc_tb):  # 如果with语句出现异常的时候会接收
        # exc_type:异常的类型
        # exc_val:异常的值
        # exc_tb:异常的回溯
        # 如果返回None,则表示上下文管理器自己处理异常,即我们认为异常已经处理完毕了,Python解释器不会将异堂传递给上层代码。
        # 如果返回True,则表示上下文管理器已经成功处理了异常,并且异常已经被处理完毕了,Python解释器不会将弃常传递给上层代码。
        # 如果返回False或其他任意非空值,则表示上下文管理器没有成功处理异常,Python解释器会将异常传递给上层代码继续处理。
        self.file_obj.close()


if __name__ == '__main__':
    with MyContextManger("demo.txt", "w") as mm:  # MyContextManger()创建对象会直接调用__init__方法
        mm.write("sssss")

with上下文管理器就是实现了 enter,__exit__方法

相关推荐
曲幽6 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805111 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞14 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派16 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪18 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户03321266636718 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫19 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派20 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风1 天前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic