学习之上下文管理器

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__方法

相关推荐
AI探索者12 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者12 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh13 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅13 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽14 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时18 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿20 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python