Python----魔法函数__enter__/__exit__的用法

时间:2025-03-04 11:45:59

【原文链接】

1、with上下文管理器的用法

  • with用的最多的可能就是打开文件,读写文件的场景,如下代码:
with open("","w+",encoding="utf8") as f:
    f.write("hello world")

其等同于如下代码:

f=open("","w+",encoding="utf8")
f.write("hello world")
f.close()

使用with语句的时候不需要显式的去关闭文件资源,因为它自动会关闭,那么这个自动关闭是怎么实现的呢,这其实就是__enter__和__exit__魔法函数在起作用

2、__enter__和__exit__魔法函数的工作原理

  • 以上面with as 的形式,那么首先是进入类函数中__enter__魔法函数,__enter__魔法函数返回结果赋值给as后面的变量,当with as 语句结束时,会自动调用__exit__魔法函数

下面重写写一个类似open的类,来实现with as 打开文件读写文件的实例,如下:


class OpenFile(object):
    def __init__(self,file_name="",mode="r",encoding="utf8",**kwargs):
        print("-----------------in init------------------")
        self.__file=open(file_name,mode,encoding=encoding)

    def __enter__(self):
        print("-----------------in enter ----------------")
        return self

    def write(self,ctx):
        print("-----------------begin write-------------")
        self.__file.write(ctx)
        print("-----------------finish write-------------")

    def __exit__(self,exec_type,exec_value,exec_tb):
        print("-----------------in exit------------------")
        self.__file.close()

with OpenFile("","w+",encoding="utf8") as f:
    f.write("hello world")

执行结果如下:

-----------------in init------------------
-----------------in enter ----------------
-----------------begin write-------------
-----------------finish write-------------
-----------------in exit------------------

因此,如果想实现一个自定义的上下文管理器,只需要在自定义类中实现这两个魔法函数即可,这里有一个关键点需要理解的就是with as 语句中as 后面的变量就是__enter__魔法函数返回值,理解了这一点,就很容易实现自己的上下文管理器了