簡體   English   中英

With 語句等於 try catch

[英]With statement equals try catch

在閱讀了一些關於它的論文后,我仍然無法理解 python 的with語句。 這兩個代碼做同樣的事情嗎? withtry catch做同樣的事情嗎?

try:
  a = A()
  #do something with a


with A() as a:
  #do something with a

不, with 語句是一個“上下文管理器”。 像這樣想:

with open(filename, "w") as file:
    do stuff in file

現在,當上面的代碼做完事情,並且執行離開 with 語句時,文件將不再打開。

請看一遍,它給出了一個很好的解釋: https : //jeffknupp.com/blog/2016/03/07/python-with-context-managers/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM