Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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__方法退出