Python中with…as…的用法詳解

簡介

  1. with是從Python2.5引入的一個新的語法,它是一種上下文管理協議,目的在於從流程圖中把 try,except 和finally 關鍵字和資源分配釋放相關代碼統統去掉,簡化try….except….finlally的處理流程。
  2. with通過__enter__方法初始化,然後在__exit__中做善後以及處理異常。所以使用with處理的對象必須有__enter__()__exit__()這兩個方法。
  3. 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語法的執行流程

  1. 首先運行expression表達式,如果表達式含有計算、類初始化等內容,會優先執行。
  2. 運行__enter()__方法中的代碼
  3. 運行with_body中的代碼
  4. 運行__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資源

代碼解析

  1. 這段代碼一共創建了2個類,第一個testclass類是功能類,用於存放定義我們需要的所有功能比如這裡的test()方法。
  2. testwith類是我們用來測試with...as...語法的類,用來給testclass類進行善後(釋放資源等)。
  3. 程序執行流程
graph TD
A[開始] –> B[創建testwith類,執行類初始化函數] –> C[進入`__enter__()`,創建testclass類] –> D[調用testclass中的test()方法] –> E[進入__exit__(),釋放資源] –> (結束)
F[豎向流程圖]
flowchat
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小車相關文章和知識。

大家對感興趣的知識點可以在文章下面留言,我可以優先幫大家講解哦

原創不易,轉載請說明出處。

Tags: