Python----魔法函数__enter__/__exit__的用法(python enter exit)

网友投稿 523 2022-08-23


Python----魔法函数__enter__/__exit__的用法(python enter exit)

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

with用的最多的可能就是打开文件,读写文件的场景,如下代码:

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

其等同于如下代码:

f=open("demo.txt","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("demo.txt","w+",encoding="utf8") as f: f.write("hello world")

执行结果如下:

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

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringBoot实现扫码登录的示例代码
下一篇:Python----魔法函数__getattr__/__setattr__/__delattr__/__getattribute__的用法(python get_attribute)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~