zoukankan      html  css  js  c++  java
  • Python With 用法

    背景

      有一些任务,可能事先需要设置,事后做清理工作。对于这种场景,Python的with语句提供了一种非常方便的处理方式。

    with如何工作?

    • 紧跟with后面的语句被求值后,返回对象的 __enter__() 方法被调用,这个方法的返回值将被赋值给as后面的变量。
    • 当with后面的代码块全部被执行完之后,将调用前面返回对象的 __exit__()方法。

    例子

    1. #!/usr/bin/env python
    2. class Test(obj):
    3.     def __enter__(self):
    4.         print "In __enter__()"
    5.               return "test_with"
    6.     def __exit__(self, type, value, trace):
    7.         print "In __exit__()"
    8. def get_example():
    9.     return Test()
    10. with get_example() as example:
    11.     print "example:", example

         大家可以做下实验看下输出.

          __exit__ 方法有三个参数 val, type 和 trace。 这些参数在异常处理中相当有用。

         实际上,在with后面的代码块抛出任何异常时,__exit__() 方法被执行。正如例子所示,异常抛出时,与之关联的type,value和stack trace传给 __exit__() 方法,因此抛出的XX异常被打印出来了。开发库时,清理资源,关闭文件等等操作,都可以放在 __exit__ 方法当中。

         另外,__exit__ 除了用于tear things down,还可以进行异常的监控和处理,注意后几个参数。要跳过一个异常,只需要返回该函数True即可。

         下面的样例代码跳过了所有的TypeError,而让其他异常正常抛出。

      1. def __exit__(self, type, value, traceback):
      2.      return isinstance(value, TypeError)

          __exit__ 函数可以进行部分异常的处理,如果我们不在这个函数中处理异常,他会正常抛出,这时候我们可以这样写

    1. try:
    2.     with open( "a.txt" ) as f :
    3.         do something
    4. except xxxError:
    5.     do something about exception
  • 相关阅读:
    973. K Closest Points to Origin
    919. Complete Binary Tree Inserter
    993. Cousins in Binary Tree
    20. Valid Parentheses
    141. Linked List Cycle
    912. Sort an Array
    各种排序方法总结
    509. Fibonacci Number
    374. Guess Number Higher or Lower
    238. Product of Array Except Self java solutions
  • 原文地址:https://www.cnblogs.com/muyiblog/p/6873609.html
Copyright © 2011-2022 走看看