網站首頁 編程語言 正文
Python中當我們們打開文本時,通常會是用with語句,with語句允許我們非常方便的使用資源,而不必擔心資源沒有關閉。
with open('/path/filename', 'r') as f:
f.read()
然而,并不是只有open()函數返回fp對象才能使用 with 語句。實際上,任何對象,只要正確實現上下文管理,就可以使用with語句。
實現上下文管理是通過 __enter__ 和 __exit__ 這兩個方法實現的。例如,下面的class實現了這兩個方法:
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 語句。
with Query('Bob') as q:
q.query()
一、@contextmanager
編寫 __enter__ 和 __exit__ 仍然很繁瑣,因此Python的標準庫 contextlib 提供了更簡單的寫法,上面的代碼可以改寫為:
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')
@contextmanager 這個裝飾器接受一個 generator,用 yield 語句把 with ... as var 把變量輸出去,然后,with 語句就可以正常的工作了:
with create_query('Bob') as q:
q.query()
很多時候,我們希望在某段代碼執行前后自動執行特定代碼,也可以用 @contextmanager實現。
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("" % name)
with tag("h1"):
print("hello")
print("world")
上述代碼執行結果:
hello
world
</h1>
代碼的執行順序是:
- with 語句 首先執行 yield 之前的語句,因此打印出.
- yield 調用會執行 with 語句內部的所有語句,因此打印出 hello 和 world.
- 最后執行yield之后的語句,打印出結果
二、@closing
如果一個對象沒有實現上下文,就不能使用 with 語句,但是可以用 closing() 來把對象變為上下文對象。
from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('https://www.python.org')) as page:
for line in page:
print(line)
closing 也是一個經過 @contextmanager 裝飾的generator
@contextmanager
def closing(thing):
try:
yield thing
finally:
thing.close()
它的作用就是把任意對象變為上下文對象,并支持 with語句。
原文鏈接:https://www.cnblogs.com/springsnow/p/13183749.html
相關推薦
- 2022-07-18 C++詳細講解print緩沖區的刷新_C 語言
- 2023-01-10 CentOS7設置ssh服務以及端口修改方式_Linux
- 2023-12-14 idea配置tomcat熱部署
- 2021-12-07 關于postman上傳文件執行成功而使用collection?runner執行失敗的問題_相關技巧
- 2022-07-09 Android中Intent的簡單使用和與Bundle的關系
- 2022-05-11 并發編程之JMM模型和并發三大特性
- 2022-12-26 python保存圖片時如何和原圖大小一致_python
- 2022-06-13 Python數據類型及常用方法_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支