pythonwith語句的原理與用法詳解-創(chuàng)新互聯(lián)

本文實(shí)例講述了python with語句的原理與用法。分享給大家供大家參考,具體如下:

成都創(chuàng)新互聯(lián)公司專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都做網(wǎng)站、網(wǎng)站設(shè)計(jì)、江夏網(wǎng)絡(luò)推廣、小程序開發(fā)、江夏網(wǎng)絡(luò)營銷、江夏企業(yè)策劃、江夏品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們大的嘉獎(jiǎng);成都創(chuàng)新互聯(lián)公司為所有大學(xué)生創(chuàng)業(yè)者提供江夏建站搭建服務(wù),24小時(shí)服務(wù)熱線:13518219792,官方網(wǎng)址:muchs.cn

關(guān)于with語句,官方文檔中是這樣描述的:

The with statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.

with_stmt ::= "with" with_item ("," with_item)* ":" suite

with_item ::= expression ["as" target]

The execution of the with statement with one “item” proceeds as follows:

The context expression (the expression given in the with_item) is evaluated to obtain a context manager.

The context manager's __exit__() is loaded for later use.

The context manager's __enter__() method is invoked.

If a target was included in the with statement, the return value from __enter__() is assigned to it.

Note


The with statement guarantees that if the __enter__() method returns without an error, then __exit__() will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. See step 6 below.

The suite is executed.

The context manager's __exit__() method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to __exit__(). Otherwise, three None arguments are supplied.

谷歌翻譯成中文就是:

(請參見使用語句上下文管理器一節(jié))。 這允許通用的try…except…finally使用模式被封裝以便于重用】。

帶有一個(gè)“項(xiàng)目”的with語句的執(zhí)行過程如下:
1.上下文表達(dá)式(在with_item中給出的表達(dá)式)被評估以獲得上下文管理器 2.上下文管理器的__exit __()被加載供以后使用
3.上下文管理器的__enter __()方法被調(diào)用
4.如果在with語句中包含目標(biāo),則將__enter __()的返回值分配給它

注意
with語句保證, 因此,如果在分配給目標(biāo)列表期間發(fā)生錯(cuò)誤,它將被視為與套件內(nèi)發(fā)生的錯(cuò)誤相同。 請參閱下面的第6步。

5.該套件已執(zhí)行意思就是語句體中的過程執(zhí)行完畢,執(zhí)行完畢就到第六步--調(diào)用__exit__()來退出】
6.上下文管理器的__exit __()方法被調(diào)用。

關(guān)于退出返回值:

If the suite was exited due to an exception, and the return value from the __exit__() method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the with statement.

If the suite was exited for any reason other than an exception, the return value from __exit__() is ignored, and execution proceeds at the normal location for the kind of exit that was taken.

中文:
如果套件由于異常而退出,并且__exit __()方法的返回值為false,則會(huì)重新對異常進(jìn)行重新評估。 如果返回值為true,則異常被抑制,并繼續(xù)執(zhí)行with語句后面的語句。

如果套件由于除了異常之外的任何原因而退出,則__exit __()的返回值將被忽略,并且執(zhí)行將在正常位置繼續(xù)進(jìn)行。


意思就是:


如果是異常退出,那么會(huì)返回false,(根據(jù)文檔中的exit的描述“that __exit__() methods should not reraise the passed-in exception; this is the caller's responsibility.”,大概意思就是exit()不會(huì)處理異常,會(huì)重新拋出異常拋出給外面,由調(diào)用者處理,因?yàn)檫@是調(diào)用者的責(zé)任)

如果返回 True,則忽略異常,不再對異常進(jìn)行處理【(在exit內(nèi)部處理完異常后,可以讓”__exit__()”方法返回True,此時(shí)該異常就會(huì)不會(huì)再被拋出,with會(huì)認(rèn)為它的執(zhí)行體沒有發(fā)生異常)】


(with會(huì)識(shí)別返回值,根據(jù)返回值來處理,如果是False,那么with會(huì)將執(zhí)行體中的異常拋出,)

附上一個(gè)文檔中提供的一個(gè)關(guān)于with中使用鎖的例子:

python with語句的原理與用法詳解

幾個(gè)測試: 1.執(zhí)行體中發(fā)生異常:
import time
class myContextDemo(object):
 def __init__(self,gen):
  self.gen = gen
 def __enter__(self):
  print("enter in ")
  return self.gen
 def __exit__(self, exc_type, exc_val, exc_tb):
#exc_type是exception_type exc_val是exception_value exc_tb是exception_trackback
  print("exit in ")
  if exc_type is None:#如果是None 則繼續(xù)執(zhí)行
   print("None:",exc_type, exc_val, exc_tb)

  else: #異常不為空時(shí)執(zhí)行,這一步,如果with語句體中發(fā)生異常,那么也會(huì)執(zhí)行
   print("exception:", exc_type, exc_val, exc_tb)
   print("all done")

if __name__=="__main__":
 gen=(i for i in range(5,10))
 G=myContextDemo(gen)
 with G as f :
  print("hello")
  for i in f:
   print(i,end="\t")
  #測試1:執(zhí)行體中發(fā)生異常
  raise Exception("母雞啊")
 print("main continue")

文章標(biāo)題:pythonwith語句的原理與用法詳解-創(chuàng)新互聯(lián)
本文來源:http://muchs.cn/article30/degdpo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動(dòng)態(tài)網(wǎng)站、App設(shè)計(jì)、全網(wǎng)營銷推廣企業(yè)網(wǎng)站制作、建站公司、手機(jī)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作