class Foo: def __init__(self,name): self.name = name def __enter__(self): print('执行enter') return self def __exit__(self, exc_type, exc_val, exc_tb): print('执行exit') print(exc_tb) #name print(exc_type) print(exc_val) #Traceback return True #返回TURE后,涵盖了前面三个 with Foo('a.txt') as f: print(f) print(abcdefg) print(f.name) print('00000000000000000000') =====>>> 执行enter <__main__.Foo object at 0x00BED4B0> 执行exit <traceback object at 0x00BF6AF8> <class 'NameError'> name 'abcdefg' is not defined 00000000000000000000