簡介
- with是從Python2.5引入的一個新的語法,它是一種上下文管理協議,目的在於從流程圖中把 try,except 和finally 關鍵字和資源分配釋放相關程式碼統統去掉,簡化try….except….finlally的處理流程。
- with通過
__enter__
方法初始化,然後在__exit__
中做善後以及處理異常。所以使用with處理的物件必須有__enter__()
和__exit__()
這兩個方法。 - with 語句適用於對資源進行訪問的場合,確保不管使用過程中是否發生異常都會執行必要的“清理”操作,釋放資源,比如檔案使用後自動關閉、執行緒中鎖的自動獲取和釋放等。舉例如下:
# 開啟1.txt檔案,並列印輸出檔案內容
with open('1.txt', 'r', encoding="utf-8") as f:
print(f.read())
看這段程式碼是不是似曾相識呢?是就對了!
With...as語句的基本語法格式:
with expression [as target]:
with_body
引數說明:
expression
:是一個需要執行的表示式;
target
:是一個變數或者元組,儲存的是expression表示式執行返回的結果,[]表示該引數為可選引數。
With...as語法的執行流程
- 首先執行
expression
表示式,如果表示式含有計算、類初始化等內容,會優先執行。 - 執行
__enter()__
方法中的程式碼 - 執行with_body中的程式碼
- 執行
__exit()__
方法中的程式碼進行善後,比如釋放資源,處理錯誤等。
例項驗證
#!/usr/bin/python3
# -*- coding: utf-8 -*-
""" with...as...語法測試 """
__author__ = "River.Yang"
__date__ = "2021/9/5"
__version__ = "1.1.0"
class testclass(object):
def test(self):
print("test123")
print("")
class testwith(object):
def __init__(self):
print("建立testwith類")
print("")
def __enter__(self):
print("進入with...as..前")
print("建立testclass實體")
print("")
tt = testclass()
return tt
def __exit__(self, exc_type, exc_val, exc_tb):
print("退出with...as...")
print("釋放testclass資源")
print("")
if __name__ == '__main__':
with testwith() as t:
print("with...as...程式內容")
print("with_body")
t.test()
程式執行結果
建立testwith類
進入with...as..前
建立testclass實體
with...as...程式內容
with_body
test123
退出with...as...
釋放testclass資源
程式碼解析
- 這段程式碼一共建立了2個類,第一個testclass類是功能類,用於存放定義我們需要的所有功能比如這裡的
test()
方法。 testwith
類是我們用來測試with...as...
語法的類,用來給testclass類進行善後(釋放資源等)。- 程式執行流程
st=>start: 開始框
op=>operation: 處理框
cond=>condition: 判斷框(是或否?)
sub1=>subroutine: 子流程
io=>inputoutput: 輸入輸出框
e=>end: 結束框
st->op->cond
cond(yes)->io->e
cond(no)->sub1(right)->op
graph TD
A[方形] --> B(圓角)
B --> C{條件a}
C --> |a=1| D[結果1]
C --> |a=2| E[結果2]
F[豎向流程圖]
A[方形] --> B(圓角)
B --> C{條件a}
C --> |a=1| D[結果1]
C --> |a=2| E[結果2]
F[豎向流程圖]
flowchat
st=>start: 開始
e=>end: 結束
op=>operation: 建立testwith類,執行類初始化函式
op1=>operation: 進入`__enter__()`,建立testclass類
op2=>operation: 呼叫testclass中的test()方法
op3=>operation: 進入__exit__(),釋放資源
st=>start: 開始
e=>end: 結束
op=>operation: 建立testwith類,執行類初始化函式
op1=>operation: 進入`__enter__()`,建立testclass類
op2=>operation: 呼叫testclass中的test()方法
op3=>operation: 進入__exit__(),釋放資源
st->op->op1->op2->op3
op3->e
歡迎各位老鐵一鍵三連,本號後續會不斷更新樹莓派、人工智慧、STM32、ROS小車相關文章和知識。
大家對感興趣的知識點可以在文章下面留言,我可以優先幫大家講解哦
原創不易,轉載請說明出處。