Python-with与contextlib简化的上下文管理器学习笔记

上下文管理器

上下文管理器with实现__enter____exit__这两个魔法函数
举个简单的例子

# 上下文管理协议
class Simple:
    def __enter__(self):
        print(1)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit")

    def doSomething(self):
        print("nothing to do")


if __name__ == '__main__':
    with Simple() as simple:
        simple.doSomething()

contextlib简化上下文管理器

contextlib修饰的函数是一个生成器

import contextlib

@contextlib.contextmanager
def file_open(file_name):
    print ("file open")
    yield {}
    print ("file end")

with file_open("bobby.txt") as f_opened:
    print ("file processing")

猜你喜欢

转载自blog.csdn.net/solitudi/article/details/106863640
今日推荐