標籤:replace microsoft yield radius 上下 sys style bottom 結果
上下文環境:
開始資訊
|
中間輸出資訊
|
結束資訊
上下文環境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()
運行結果:
BeginQuery info about Bob...EndQuery info about Bob...
上下文環境2:@contextmanager
from contextlib import contextmanagerclass Query(object): def __init__(self, name): self.name = name def query(self): print('Query info about %s...' % self.name)@contextmanagerdef create_query(name): print('Begin') q = Query(name) yield q print('End') with create_query('Bob') as q: q.query()
運行結果:
BeginQuery info about Bob...End
上下文環境3:@contextmanager 再次簡化
from contextlib import contextmanager@contextmanagerdef tag(name): print("<%s>" % name) yield print("</%s>" % name)with tag("h1"): print("hello") print("world")
上述代碼執行結果為:
<h1>helloworld</h1>
沒有上下文環境:@closing 通過closing()來把該對象變為內容物件,例如,用with語句使用urlopen():
from contextlib import closingfrom urllib.request import urlopenwith 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@contextmanagerdef closing(thing): try: yield thing finally: thing.close()
上述代碼執行結果為:
python 裝飾器:contextlib