python 魔术方法__enter__及__exit__上下文管理方法



上下文管理器协议 __enter__ __exit__方法

with:上下文管理器协议:
__enter__:进入上下文(with操作对象时)
__exit__:退出上下文(with中的代码块执行完毕之后)
with是用来启动对象的上下文协议的,不是用来专门操作文件的

使用with语句的时候不需要显式的去关闭文件资源,因为它自动会关闭,
那么这个自动关闭是怎么实现的呢,这其实就是__enter__和__exit
__魔法方法在起作用.
with as 语句中as 后面的变量就是__enter__魔法函数返回值

with open("text.txt", mode="r", encoding="utf-8")as a:  # __enter__:进入上下文(with操作对象时)
      那么此时a 就是enter方法的返回值,进入上下文的
     print(a.read())  # 执行对象当中的内容

print(a.read())
此时在我with执行完成 之后会调用__exit__方法,结束会话,此时在外部调用时,提示异常
ValueError: I/O operation on closed file. #文件没有打开

  

自定义一个实现读取文件关闭的方法


class OpenFile:


    def __init__(self,filepath,mode,encoding="utf-8"):
        self.file =  open(file=filepath,mode=mode,encoding=encoding)

    def __enter__(self):
        print("-------------进入上下文会话------------")
        return self.file.read()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()
        print("-------------结束上下文会话------------")


# a = OpenFile("text.txt", mode="r", encoding="utf-8")
# with a as s:
#     print(s)

"""
输出结果:
-------------进入上下文会话------------
dddd
pppp
-------------结束上下文会话------------

"""

  

 

原文地址:http://www.cnblogs.com/manxingsir/p/16852193.html

发表评论

您的电子邮箱地址不会被公开。