【python3】with的用法

使用的基本思想大致是with所求值的对象必须有一个enter()方法和一个exit()方法。下面给一个简单的例子去说明使用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)

1.with开始,enter()方法被执行

2.enter()方法返回的值 - 这个例子中是Foo,赋值给变量sample

3.执行代码块,打印变量sample的值为 Foo

4.exit()方法被调用 with真正强大之处是它可以处理异常。注意到Sample类的exit方法有三个参数- val, type 和 trace。 这些参数在异常处理中相当有用。

转载 https://www.cnblogs.com/wangjian1226/p/10521880.html

猜你喜欢

转载自www.cnblogs.com/Carits/p/12817227.html