pythonwith语句的原理与用法详解-创新互联

本文实例讲述了python with语句的原理与用法。分享给大家供大家参考,具体如下:

成都创新互联公司专注为客户提供全方位的互联网综合服务,包含不限于成都做网站、网站设计、江夏网络推广、小程序开发、江夏网络营销、江夏企业策划、江夏品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们大的嘉奖;成都创新互联公司为所有大学生创业者提供江夏建站搭建服务,24小时服务热线:13518219792,官方网址:www.cdcxhl.com

关于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.

谷歌翻译成中文就是:

(请参见使用语句上下文管理器一节)。 这允许通用的try…except…finally使用模式被封装以便于重用】。

带有一个“项目”的with语句的执行过程如下:
1.上下文表达式(在with_item中给出的表达式)被评估以获得上下文管理器 2.上下文管理器的__exit __()被加载供以后使用
3.上下文管理器的__enter __()方法被调用
4.如果在with语句中包含目标,则将__enter __()的返回值分配给它

注意
with语句保证, 因此,如果在分配给目标列表期间发生错误,它将被视为与套件内发生的错误相同。 请参阅下面的第6步。

5.该套件已执行意思就是语句体中的过程执行完毕,执行完毕就到第六步--调用__exit__()来退出】
6.上下文管理器的__exit __()方法被调用。

关于退出返回值:

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,则会重新对异常进行重新评估。 如果返回值为true,则异常被抑制,并继续执行with语句后面的语句。

如果套件由于除了异常之外的任何原因而退出,则__exit __()的返回值将被忽略,并且执行将在正常位置继续进行。


意思就是:


如果是异常退出,那么会返回false,(根据文档中的exit的描述“that __exit__() methods should not reraise the passed-in exception; this is the caller's responsibility.”,大概意思就是exit()不会处理异常,会重新抛出异常抛出给外面,由调用者处理,因为这是调用者的责任)

如果返回 True,则忽略异常,不再对异常进行处理【(在exit内部处理完异常后,可以让”__exit__()”方法返回True,此时该异常就会不会再被抛出,with会认为它的执行体没有发生异常)】


(with会识别返回值,根据返回值来处理,如果是False,那么with会将执行体中的异常抛出,)

附上一个文档中提供的一个关于with中使用锁的例子:

python with语句的原理与用法详解

几个测试: 1.执行体中发生异常:
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 则继续执行
   print("None:",exc_type, exc_val, exc_tb)

  else: #异常不为空时执行,这一步,如果with语句体中发生异常,那么也会执行
   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:执行体中发生异常
  raise Exception("母鸡啊")
 print("main continue")

分享标题:pythonwith语句的原理与用法详解-创新互联
URL地址:http://bzwzjz.com/article/degdpo.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 成都h5网站建设 网站制作 手机网站建设 成都网站设计 成都网站建设 成都网站设计公司 成都网站设计制作公司 成都商城网站建设 成都网站制作 成都网站制作 成都品牌网站建设 成都网站建设 成都网站建设 品牌网站建设 专业网站设计 成都网站建设 成都网站建设 自适应网站建设 企业网站建设 成都网站建设 网站制作 营销网站建设