python with 实现

python with 实现

当我们利用python打开一个文件,我们通常都是使用with关键词,但with又是如何实现的?

python核心使用__enter__和__exit__两个私有方法,在类的进入的过程中,会先调用__enter__方法,然后进行响应的逻辑处理,之后在结束之后会调用__exit__方法。

我们可以使用with进行数据库连接,__enter__进行数据库的初始化,__exit__进行数据库的断开连接。

实现一个打开文件的实现。

class OpenFile:
    def __init__(self, filename):
        self.filename = filename
        self.writer = None
        
    def __enter__(self):
        """
        __enter__ Main logic happens here.
        """
        print('start to open file: {}'.format(self.filename))
        self.writer = open(self.filename, 'a+')
        # __enter must return self
        return self
    
    def write(self, content):
        self.writer.write(content)
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Now to stop")
        self.writer.close()
        
    
if __name__ == '__main__':
    with OpenFile('test.txt') as openfile:
        openfile.write('this is to test with content\n')
        openfile.write('add one more line.')

然后我们就可以通过with的方法打开一个文件,同时写入内容到这个文件中。

posted @ 2021-12-24 10:16  蒙奇LU  阅读(81)  评论(0)    收藏  举报