python的with是如何工作的

来源:互联网 发布:淘宝网床上四件套纯棉 编辑:程序博客网 时间:2024/06/16 01:48
class Sample:    def __enter__(self):        print "In __enter__()"        return "Foo"     def __exit__(self, type,value, trace):        print "In __exit__()"def get_sample():    return Sample()  with get_sample() as sample:    print "sample:",sample

运行结果

In __enter__()

sample: Foo

In __exit__()

原理:

1. __enter__()方法被执行
2. __enter__()方法返回的值 - 这个例子中是"Foo",赋值给变量'sample'
3. 执行代码块,打印变量"sample"的值为 "Foo"
4. __exit__()方法被调用


with真正强大之处是它可以处理异常

class Sample:    def __enter__(self):        return self     def __exit__(self, type,value, trace):        print "type1:", type        print "value:",value        print "trace:",trace    def do_something(self):        bar = 1/0        return bar + 10 with Sample() as sample:    sample.do_something()

运行结果:

type1: <type 'exceptions.ZeroDivisionError'>
value: integer division or modulo by zero
trace: <traceback object at 0x0000000002568748>
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 14, in <module>
    sample.do_something()
  File "C:\Users\Administrator\Desktop\test.py", line 10, in do_something
    bar = 1/0
ZeroDivisionError: integer division or modulo by zero


所以,异常处理可以放在__exit__()中



0 0