上下文管理器

上下文管理器:实现__enter__方法和__exit__方法的类就是一个上下文管理器:

示例代码:

from contextlib import ContextDecorator
class Mycontext(ContextDecorator):
    def __enter__(self):
        print('start')


    def __exit__(self, exc_type, exc_val, exc_tb):
        print('end')


@Mycontext()
def test():
    print('hello')

test()

 

posted @ 2019-12-01 22:37  王军的个人博客  阅读(106)  评论(0编辑  收藏  举报