class Foo(object): def func(self): print("func") pass def __enter__(self): print("enter") return Foo() def __exit__(self, exc_type, exc_val, exc_tb): print("close") # with语句时调用__enter__()方法,该方法的返回值就是e with Foo() as e: e.func() # with缩进内容技术时自动调用__exit__()方法 # 打印顺序 # enter # func # close