首页 > 其他 > 详细

上下文管理器 contextlib

时间:2018-04-17 19:00:22      阅读:164      评论:0      收藏:0      [点我收藏+]
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

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

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