python 装饰器:contextlib
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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("h1"): print("hello") print("world")
上述代码执行结果为:
<h1> hello world </h1>
没有上下文环境:@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> ' b'<head> ' b' <script> ' b' location.replace(location.href.replace("https://","http://")); ' b' </script> ' b'</head> ' b'<body> ' b' <noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript> ' b'</body> ' b'</html>'
不懂怎么验证的closing
from contextlib import contextmanager @contextmanager def closing(thing): try: yield thing finally: thing.close()
上述代码执行结果为:
以上是关于python 装饰器:contextlib的主要内容,如果未能解决你的问题,请参考以下文章