簡介
- 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小車相關文章和知識,
大家對感興趣的知識點可以在文章下面留言,我可以優先幫大家講解哦
原創不易,轉載請說明出處,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/301160.html
標籤:Python
