笔记-python-statement-with

笔记-python-statement-with

1.      with语句

1.1.    基础使用案例

在开发时,经常使用with语句来打开文件:

with open(‘a.txt’,’a+’,encoding=’utf-8’) as fi:

       data = fi.read()

从效果上而言上一句话等效于下文

try:

    f = open('xxx')

except:

    print 'fail to open'

    exit(-1)

try:

    do something

except:

    do something

finally:

     f.close()

1.2.    with原理

with其实等效于try…except…finally语句,

with语句执行步骤如下所述:

  1. 上下文声明生成一个上下文管理器;
  2. 上下文管理器的__exit__()方法被加载以待后续使用;
  3. 上下文管理器的__enter__()方法被引用执行;
  4. 如果with语句完成,__enter__()的返回值被赋与;
  5. 执行suite套件;
  6. 上下文管理器的__exit__()方法被引用执行。如果suite执行发生异常,异常的type,value,traceback作为参数传给__exit__(),否则传送三个none。

如果suite以异常结束,而且__exit__()的返回值是false,抛出异常;如果__exit__()返回值是true,异常被处理,会执行接下来的语句。

with A() as a, B() as b:

       suite

等效于:

with A() as a:

       with B() as b:

              suite

1.3.    context manager

文档位于https://docs.python.org/3/reference/datamodel.html#special-method-names

context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are normally invoked using the with statement (described in section The with statement), but can also be used by directly invoking their methods.

Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc.

For more information on context managers, see Context Manager Types.

核心是两个方法:

object.__enter__(self)

Enter the runtime context related to this object. The withstatement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.

简单来说,enter()的返回值会绑定到as分钟所声明的对象上。

object.__exit__(self, exc_type, exc_value, traceback)

Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be None.

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.

Note that __exit__() methods should not reraise the passed-in exception; this is the caller’s responsibility.

1.4.    参考文档

https://docs.python.org/3/reference/compound_stmts.html#the-with-statement

https://docs.python.org/3/reference/datamodel.html#special-method-names

猜你喜欢

转载自www.cnblogs.com/wodeboke-y/p/10381054.html