码迷,mamicode.com
首页 > 其他好文 > 详细

上下文管理器 contextlib

时间:2018-04-17 19:57:30      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:语句   name   工作   sel   rom   编写   elf   输出   foo   

from contextlib import contextmanager

@contextmanager
def tag(name):
    print "<%s>" % name
    yield
    print "</%s>" % name

>>> with tag("h1"):
...    print ("foo")
...
<h1>
foo
</h1>

编写 __enter__ 和 __exit__ 仍然很繁琐,因此Python的标准库 contextlib 提供了更简单的写法

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

from contextlib import contextmanager
 
class Query(object):
 
    def __init__(self, name):
        self.name = name
 
    def query(self):
        print(‘Query info about %s...‘ % self.name)
 
@contextmanager
def create_query(name):
    print(‘Begin‘)
    q = Query(name)
    yield q
    print(‘End‘)
with create_query(‘Bob‘) as q:
    q.query()

 

上下文管理器 contextlib

标签:语句   name   工作   sel   rom   编写   elf   输出   foo   

原文地址:https://www.cnblogs.com/Erick-L/p/8868540.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!