首页 > 其他 > 详细

二十二、with与'上下文管理器'

时间:2020-04-09 12:53:52      阅读:50      评论:0      收藏:0      [点我收藏+]

系统资源如文件、数据库连接、socket等,应用程序打开这些资源并执行完业务逻辑之后,必须关闭(断开)该资源,否则会出现资源占用的情况。

普通版的打开文件:

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

使用了try except的打开文件的方式:

 f = open("output.txt", "w")
    try:
        f.write("python之禅")
    except IOError:
        print("oops error")
    finally:
        f.close()

使用with打开文件的方式:

with open("output.txt", "r") as f:
        f.write("Python之禅")

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

 

上下文管理器

  任何实现了__enter__()和__exit__()方法的对象都可称为上下文管理器。

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()

  __enter__() 方法返回资源对象,这里就是你将要打开的那个文件对象,__exit__() 方法处理一些清除工作。因为 File 类实现了上下文管理器,现在就可以使用 with 语句了。

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

  这样无需显示地调用 close 方法了,由系统自动去调用,哪怕中间遇到异常 close 方法也会被调用。

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

  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")

 

二十二、with与'上下文管理器'

原文:https://www.cnblogs.com/nuochengze/p/12666088.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!