您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
上下文环境:
开始信息
|
中间输出信息
|
结束信息
上下文环境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")
上述代码执行结果为:
<h2> hello world </h2>
没有上下文环境:@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'<html>\r\n' b'<head>\r\n' b'\t<script>\r\n' b'\t\tlocation.replace(location.href.replace("https://","http://"));\r\n' b'\t</script>\r\n' b'</head>\r\n' b'<body>\r\n' b'\t<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>\r\n' b'</body>\r\n' b'</html>'
不懂怎么验证的closing
from contextlib import contextmanager @contextmanager def closing(thing): try: yield thing finally: thing.close()
上述代码执行结果为:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。