python的with是如何工作的

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值