会员登录|免费注册|忘记密码|管理入口 你好,欢迎访问!  返回主站|手机浏览|联系方式

杭州小码教育科技有限公司  
加关注1

少儿AI编程培训

搜索
新闻分类
侧栏站内搜索
 
侧栏联系方式
  • 联系人:童老师
  • 电话:4000596872
  • 邮件:3268851033@qq.com
  • 手机:18757550914
  • 微信:18757550914
首页 > 小码资讯 > Python编程教程七十四:上下文库
小码资讯
Python编程教程七十四:上下文库
2023-08-254

在Python中,读写文件这样的资源要特别注意,必须在使用完毕后正确关闭它们。正确关闭文件资源的一个方法是使用try...finally:

try:
    f = open('/path/to/file', 'r')
    f.read()finally:
    if f:
        f.close()

try...finallyPython的with语句我们方便地使用资源,而不必担心资源没有关闭,所以上面的代码可以简化为:

with open('/path/to/file', 'r') as f:
    f.read()

不是只有open()函数返回的fp对象才能使用with语句。实际上,任何对象,只要正确实现了上下文管理,就可以用于with语句。

实现上下文管理是通过__enter__和__exit__这两个方法实现的。例如,下面的类实现了这两个方法:

class Query(object):
    def __init__(self, name):
        self.name = name
    def __enter__(self):
        print('Begin')
        return self
    
    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type:
            print('Error')
        else:
            print('End')
    
    def query(self):
        print('Query info about %s...' % self.name)

这样我们就可以把自己写的资源对象用于with语句:

with Query('Bob') as q:
    q.query()

@contextmanager

编写起来__enter__仍然__exit__很繁琐,因此Python的标准库contextlib提供了更简单的写法,上面的代码可以改写如下:

from contextlib import contextmanagerclass Query(object):
    def __init__(self, name):
        self.name = name
    def query(self):
        print('Query info about %s...' % self.name)@contextmanagerdef create_query(name):
    print('Begin')
    q = Query(name)
    yield q
    print('End')

@contextmanager这个装饰器接受一个生成器,用yield语句把with ... as var变量输出出去,然后,with语句就可以正常工作了:

with create_query('Bob') as q:
    q.query()

很多时候,我们希望在某段代码执行交互自动特定执行代码,也可以用@contextmanager实现。例如:

@contextmanagerdef tag(name):
    print(<%s> % name)
    yield
    print(</%s> % name)with tag(h1):
    print(hello)
    print(world)

问题执行代码结果为:

<h1>helloworld</h1>

代码的执行顺序是:

  1. with语句首先执行yield之前的语句,因此打印出<h1>;

  2. yield调用会执行with语句内部的所有语句,因此打印出hello和world;

  3. 最后执行yield之后的语句,打印出</h1>。

因此,@contextmanager让我们通过编写生成器来简化上下文管理。

@结束

如果一个对象没有实现上下文,我们就不能把它用于with语句。这个时候,可以closing()用来将该对象当作上下文对象。例如,用with语句使用urlopen():

from contextlib import closingfrom urllib.request import urlopenwith closing(urlopen('https://www.python.org')) as page:
    for line in page:
        print(line)

closing也是一个经过@contextmanager装饰的生成器,这个生成器编写起来其实非常简单:

@contextmanagerdef closing(thing):
    try:
        yield thing
    finally:
        thing.close()

它的作用就是把任何一个对象当作上下文对象,并支持with语句。

@contextlib还有其他一些装饰器,我们编写了更简洁的代码。【本文分享源至:LmCjl社区网】