__enter__和__exit__上下文管理协议
# __enter__和__exit__上下文管理协议 f = open('test.txt', 'r', encoding='utf-8') f.read() f.close() # 等同于下面的with...as...写法,实际上就是实现了上下文管理协议,无需再关闭f对象 with open('test.txt', 'r', encoding='utf-8') as f: f.read() class Open: def __init__(self, name): self.name = name def __enter__(self): print('执行enter') return self # with中的代码块出现异常时或执行完with后就会调用__exit__ def __exit__(self, exc_type, exc_val, exc_tb): print('执行exit') print(exc_type) # 异常类名 print(exc_val) # 异常的值 print(exc_tb) # 异常的追踪信息 return True # return True时,当with中的代码块出现异常时,程序不会报错 with Open('test.txt') as f: pass