class Foo(object): def __init__(self): pass def __enter__(self): print("__enter__") def __exit__(self, exc_type, exc_val, exc_tb): print("__exit__") obj = Foo() with obj: print("xxx") # 结果 """ __enter__ xxx __exit__ """