with open as f原理解析

1.with语句的原理:

  1.1with是对类进行操作,必须包括以下三个函数

    1.1.1    def __enter__(self):return self     必须返回自己

    1.1.2    def __exit__(self, exc_type, exc_val, exc_tb):关闭类之前做的操作

    1.1.3    具体做事情的函数,名字随便起

2.直接见代码:

class OPEN():
    def __enter__(self):
        print("in")
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("out")

    def do_something(self):
        print("做一些事情")
with OPEN() as f:
    f.do_something()
View Code

 

  

posted @ 2021-10-07 21:33    阅读(389)  评论(0编辑  收藏  举报