with

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:%s" % sample)

运行代码,输出如下

In __enter__()
sample: Foo
In __exit__()

先执行__enter__方法,最后执行__exit__方法退出

最后更新于

这有帮助吗?