Python--with

with 语块定义了 运行时刻上下文环境;
在执行 with 语句时将“进入”该上下文环境,而执行该语块中的最后一条语句将“退出”该上下文环境。
 
with后面跟的对象必须有一个__enter__()方法,一个__exit__()方法。
所编写代码
Python 实际调用
with x:
x.__enter__()
with x:
x.__exit__()
  1. __enter__() 方法将始终返回 self —— 这是 with 语块将用于调用属性和方法的对象
  2. 在 with 语块结束后,文件对象将自动关闭。在 __exit__() 方法中调用了 self.close() 
 
个人理解
__enter__()类似于前置钩子,__exit__()类似于后置钩子
 
1.在文件处理中的使用
with open("/tmp /foo.txt") as file:
    data = file.read()
 
2.使用with处理异常
class Sample:
    def __enter__(self):
        return self

    def __exit__(self, type, value, trace):    #在with后面的代码块抛出任何异常时,__exit__()方法被执行
        print "type:", type
        print "value:", value
        print "trace:", trace

    def do_something(self):
        bar = 1/0
        return bar + 10

with Sample() as sample:
    sample.do_something()
代码执行后:
type: <type 'exceptions.ZeroDivisionError'>
value: integer division or modulo by zero
trace: <traceback object at 0x1004a8128>
Traceback (most recent call last):
  File "./with_example02.py", line 19, in <module>
    sample.do_somet hing()
  File "./with_example02.py", line 15, in do_something
    bar = 1/0
ZeroDivisionError: integer division or modulo by zero
 

原文地址:https://www.cnblogs.com/absoluteli/p/14090076.html