学习之上下文管理器

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

相关推荐
Flittly11 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling15 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook19 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风20 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风20 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780512 天前
Python 实现 PPT 转 HTML
后端·python
zone77392 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77392 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm