python--with语法和上下文管理器

with与“上下文管理器”

上下文管理器

  • 任何实现了 __enter__() 和 __exit__() 方法的对象都可称之为上下文管理器
  • 上下文管理器对象可以使用 with 关键字。显然,文件(file)对象也实现了上下文管理器。
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()


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

实现上下文管理器的另外方式

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

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

调用

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

猜你喜欢

转载自blog.csdn.net/lb786984530/article/details/81193114