学习之上下文管理器

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

相关推荐
m5655bj21 分钟前
Python 查找并高亮显示指定 Excel 数据
开发语言·python·excel
诗句藏于尽头31 分钟前
TCP、UDP 和串口通信-学习笔记
学习·tcp/ip·udp
shenghaide_jiahu42 分钟前
数学分析简明教程——3.5
学习
武子康1 小时前
Java-167 Neo4j CQL 实战:CREATE/MATCH 与关系建模速通 案例实测
java·开发语言·数据库·python·sql·nosql·neo4j
upward_tomato1 小时前
python中模拟浏览器操作之playwright使用说明以及打包浏览器驱动问题
开发语言·python
为你写首诗ge1 小时前
【python】python安装使用pytorch库环境配置
pytorch·python
信创天地1 小时前
RISC-V 2025年在国内的发展趋势
python·网络安全·系统架构·系统安全·运维开发
Danceful_YJ1 小时前
30.注意力汇聚:Nadaraya-Watson 核回归
pytorch·python·深度学习
FreeCode1 小时前
LangChain1.0智能体开发:人机协作
python·langchain·agent
2501_930412272 小时前
如何添加清华源到Conda?
开发语言·python·conda