簡介
- 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類進行善后(釋放資源等)。- 程序執行流程

歡迎各位老鐵一鍵三連,本號后續會不斷更新樹莓派、人工智能、STM32、ROS小車相關文章和知識。
大家對感興趣的知識點可以在文章下面留言,我可以優先幫大家講解哦
原創不易,轉載請說明出處。
