python 中 with as的用法

2021-06-15 08:57:50 字數 1537 閱讀 7588

with從python 2.5就有,需要from __future__ import with_statement。

自python

2.6開始,成為預設關鍵字。

在what's new in python2.6/3.0中,明確提到:

the 『

with

『 statement is a control-flow structure whose basic

structure is:

with expression [as variable]:

with-block

也就是說with是乙個控制流語句,跟if/for/while/try之類的是一類的,with可以用來簡化try finally**,看起來可以比try finally更清晰。

這裡新引入了乙個"上下文

管理協議"context management protocol,實現方法是為乙個類定義__enter__和__exit__兩個函式。

with expresion as variable的執行過程是,首先執行__enter__函式,它的返回值會賦給as後面的variable,想讓它返回什麼就返回什麼,只要你知道怎麼處理就可以了,如果不寫as variable,返回值會被忽略。

然後,開始執行with-block中的語句,不論成功失敗(比如發生異常、錯誤,設定sys.exit()),在with-block執行完成後,會執行__exit__函式。

這樣的過程其實等價於:

try:

執行 __enter__的內容

執行 with_block.

finally:

執行 __exit__內容

只不過,現在把一部分**封裝成了__enter__函式,清理**封裝成__exit__函式。

我們可以自己實現乙個例子:

import sys

class test:

def __enter__(self):

print("enter")

return 1

def __exit__(self,*args):

print("exit")

return true

with test() as t:

print("t is not the result of test(), it is __enter__ returned")

print("t is 1, yes, it is ".format(t))

raise nameerror("hi there")

sys.exit()

print("never here")

注意:1,t不是test()的值,test()返回的是"context manager object",是給with用的。t獲得的是__enter__函式的返回值,這是with拿到test()的物件執行之後的結果。t的值是1.

2,__exit__函式的返回值用來指示with-block部分發生的異常是否要re-raise,如果返回false,則會re-raise with-block的異常,如果返回true,則就像什麼都沒發生。

Python中with as的用法

這個語法是用來代替傳統的try.finally語法的。with expression as variable with block 基本思想是with所求值的物件必須有乙個 enter 方法,乙個 exit 方法。緊跟with後面的語句被求值後,返回物件的 enter 方法被呼叫,這個方法的返回值將...

Python中的with as 語法

使用語言的好特性,而不是那些糟糕的特性 不知道誰說的 好久不學習python的語法了,上次去面試,和面試官聊到了python中的with as statement 也稱context manager 挺感興趣的,這兩天學習了一番,收穫頗豐在此分享。先說明乙個常見問題,檔案開啟 1 2 34 5 6 ...

Python中的with as 語法

1 使用with.as.的原因 python操作檔案時,需要開啟檔案,最後手動關閉檔案。通過使用with.as.不用手動關閉檔案。當執行完內容後,自動關閉檔案。2 先說明乙個常見問題,檔案開啟 try f open do something except do something finally f...