class A: def __init__(self): print('__init__()') def __enter__(self): print('__enter__()') def __exit__(self, exc_type, exc_val, exc_tb): print('__exit__()') with A() as a: print('run')
结果:
__init__() __enter__() run __exit__()