学习之上下文管理器

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

相关推荐
u01092727117 分钟前
RESTful API设计最佳实践(Python版)
jvm·数据库·python
我材不敲代码4 小时前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
0思必得06 小时前
[Web自动化] Selenium处理动态网页
前端·爬虫·python·selenium·自动化
韩立学长6 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
qq_192779876 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u0109272717 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊7 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
Imm7777 小时前
中国知名的车膜品牌推荐几家
人工智能·python
tudficdew8 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd6528 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python