python当中自定义上下文管理器

在python当中,我们知道with的用法,是一种上下文管理机制。比如with open(file,'w') as f:  这种方法下,就集成了open和close.我们也可以自定义一个上下文管理器。

方法一:

class Content(object):
    def __init__(self,filename,mode,encoding='utf-8'):
        self.filename = filename
        self.mode = mode
        self.encoding = encoding

    def __enter__(self):
        self.f = open(self.filename,self.mode)
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()

    def do_something(self):
        print('hello world')

with Content('content_test.txt','a') as f:
    f.write('bruce 是个美男')
View Code

注意事项:

  必须要有__enter__和__exit__两个魔术方法。

 

方法二:

import contextlib

@contextlib.contextmanager
def hander_file(filename,mode):
    print('---before yield---')
    f = open(filename,mode)
    yield f
    print('---after yield ---')
    f.close()

with hander_file('.\content_test.txt','a') as f:
    print('hander_file')
    f.write("hello world \n")

使用 contextlib.contextmanager 装饰器,可以将一个函数变为一个上下文管理器,不过要求这个被修饰的函数必须为一个生成器。所以,函数中药有yield的存在

 

posted on 2022-10-20 11:00  一先生94  阅读(78)  评论(0编辑  收藏  举报

导航