您好,登錄后才能下訂單哦!
上下文環境:
開始信息
|
中間輸出信息
|
結束信息
上下文環境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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。