Python with关键字,上下文管理器,@contextmanager

demo.py(with 打开文件):

# open 方法的返回值赋值给变量 f,当离开 with 代码块的时候,系统会自动调用 f.close() 方法
# with 的作用和使用 try/finally 语句是一样的。

with open("output.txt", "r") as f:
    f.write("XXXXX")

demo.py(with,上下文管理器):

# 自定义的MyFile类
# 实现了 __enter__() 和 __exit__() 方法的对象都可称之为上下文管理器
class MyFile():

    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

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

    # with代码块执行完或者with中发生异常,就会自动执行__exit__方法。
    def __exit__(self, *args):
        print("will exit")
        self.f.close()


# 会自动调用MyFile对象的__enter__方法,并将返回值赋给f变量。
with MyFile('out.txt', 'w') as f:
    print("writing")
    f.write('hello, python')
    # 当with代码块执行结束,或出现异常时,会自动调用MyFile对象的__exit__方法。

demo.py(实现上下文管理器的另一种方式):

from contextlib import contextmanager

@contextmanager
def my_open(path, mode):
    f = open(path, mode)
    yield f
    f.close()


# 将my_open函数中yield后的变量值赋给f变量。
with my_open('out.txt', 'w') as f:
    f.write("XXXXX")
    # 当with代码块执行结束,或出现异常时,会自动执行yield后的代码。

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/84744135