Python高级语法-私有属性-with上下文管理器(4.7.3)

@

1.说明

上下文管理器
这里使用with open操作文件,让文件对象实现了自动释放资源。我们也能自定义上下文管理器,通过__enter__()和__exit__()这两个魔术方法来自定义的操作文件
当有上下文使用的场景的时候,如打开一个东西要关闭,像等文件等资源,就可以使用这种方式去定义一个上下文管理器

2.代码

class File():
    def __init__(self,filename,mode):
        self.filename  = filename
        self.mode = mode

    def __enter__(self):
        print("__enter__")
        self.f = open(self.filename,self.mode,encoding="utf-8")
        return self.f

    def  __exit__(self, exc_type, exc_val, exc_tb):
        print("__exit__")
        self.f.close()


with File("魔方方法.py","r") as f:
    print(f.read())

关于作者

个人博客网站
个人GitHub地址
个人公众号:
在这里插入图片描述

原文地址:https://www.cnblogs.com/simon-idea/p/11412247.html