python装饰器:contextlib-创新互联
上下文环境:

开始信息
|
中间输出信息
|
结束信息
上下文环境1:
#!/usr/bin/python
# -*- coding: utf-8 -*-
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 Query('Bob') as q:
q.query()
Query('Bob').query()运行结果:
Begin Query info about Bob... End Query info about Bob...
上下文环境2:@contextmanager
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()运行结果:
Begin Query info about Bob... End
上下文环境3:@contextmanager 再次简化
from contextlib import contextmanager
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("%s>" % name)
with tag("h2"):
print("hello")
print("world")上述代码执行结果为:
hello world
没有上下文环境:@closing 通过closing()来把该对象变为上下文对象,例如,用with语句使用urlopen():
from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('https://www.baidu.com')) as page:
for line in page:
print(line)上述代码执行结果为:
b'\r\n' b'\r\n' b'\t\r\n' b'\r\n' b'\r\n' b'\t\r\n' b'\r\n' b''
不懂怎么验证的closing
from contextlib import contextmanager @contextmanager def closing(thing): try: yield thing finally: thing.close()
上述代码执行结果为:
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
文章名称:python装饰器:contextlib-创新互联
转载源于:http://www.jxjierui.cn/article/deiihd.html


咨询
建站咨询
