python上下文管理協議,即with的詳細使用

來源:互聯網
上載者:User

標籤:部分   清理   __enter__   組成   self   需要   fine   post   recent   

一、with obj as f:

#代碼塊...

 

二、執行流程:

1.with obj --->觸發obj.__enter__(),需要在obj裡寫__enter__(self),在它裡邊寫傳回值,返回給 as f 

2.with obj as f 等同於 f = obj.__enter__()

3.執行with代碼塊裡的程式

4.執行正常時,順序執行obj中的__exit__()方法,exc_type, exc_val, exc_tb的值都是None.

存在異常時,__exit__()方法中

a. return False返回假時,拋出系統異常。

b. return True 返回假時,吞掉系統異常,自己定製異常資訊。

 

三、它的作用:自動清理/釋放代碼塊中程式佔用的資源,無須考慮這些問題

class Foo:    def __init__(self,aa):        self.aa = aa    def __enter__(self):        print(‘run enter‘)        return self    def __exit__(self, exc_type, exc_val, exc_tb):        print(‘run exit‘)        print(exc_type)#異常類 如:NameError        print(exc_val)#異常值 如:name ‘myname‘ is not defined        print(exc_tb)#追蹤資訊 如:Traceback (most recent call last): xxxx        return Truewith Foo(11) as cc:    print(cc.aa)    print(cc.ff)print(‘ssss‘)

 

 

常見的異常組成部分

Traceback (most recent call last):(追蹤資訊開始)

  File "D:/workSpace/purePython3/異常.py", line 1, in <module>

    myname(追蹤資訊結束)

NameError(異常類): name ‘myname‘ is not defined(異常值)

 

python上下文管理協議,即with的詳細使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.