Python高级——with上下文管理器

with上下文管理器

  任何实现了 enter() 和 exit() 方法的对象都可称之为上下文管理器,上下文管理器对象可以使用 with 关键字。
  
如果一个一个文件使用普通方式打开:

def m1():
    f = open("output.txt", "w")
    f.write("python之禅")
    f.close()

如果程序执行中碰到错误,会退出程序,可能没有执行f.close(),会造成系统资源的浪费。

如果使用with方式:

with File('out.txt', 'w') as f:
    print("writing")
    f.write('hello, python')

如果程序执行中碰到错误,会自动关闭文件。

自定义上下文管理器:

class File():

    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

    def __exit__(self, *args):
        print("will exit")
        self.f.close()

实现上下文管理器的另一种方式:

from contextlib import contextmanager

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

  Python 还提供了一个 contextmanager 的装饰器,更进一步简化了上下文管理器的实现方式。通过 yield 将函数分割成两部分,yield 之前的语句在 enter 方法中执行,yield 之后的语句在 exit 方法中执行。紧跟在 yield 后面的值是函数的返回值。
  
调用:

with my_open('out.txt', 'w') as f:
    f.write("hello , the simplest context manager")

猜你喜欢

转载自blog.csdn.net/zsh142537/article/details/82685598