'''上下文管理协议__enter__和__exit__''' with open('day62.py', 'r') as f: pass # 上述叫做上下文管理协议,即with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明__enter__和__exit__方法 # class Open: # def __init__(self, name): # self.name = name # # def __enter__(self): # print('出现with语句,对象的__enter__被触发,有返回值则赋值给as声明的变量') # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # print('with中代码块执行完毕时执行我啊') # print(exc_type) # with代码块无异常,打印None # print(exc_val) # with代码块无异常,打印None # print(exc_tb) # with代码块无异常,打印None # # with Open('a.txt') as f1: # print('===>执行代码块') # 先触发执行__enter__,然后执行with中代码,最后执行__exit__ # print(f1) # <__main__.Open object at 0x0000014AD1A58490> (Open类中__enter__返回的是实例本身,如果没有返回则打印None) # print(f1.name) # a.txt (如果Open类中__enter__没有返回实例本身,那么调用不到此实例属性) # class Open_1: # def __init__(self, name): # self.name = name # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # print(exc_type) # <class 'NameError'> 对应异常类 # print(exc_val) # name 'ababab' is not defined 对应异常值 # print(exc_tb) # <traceback object at 0x0000027C6F1A1D40> 对应异常追踪信息 # # with Open_1('b.txt') as f2: # print(ababab) # 无此变量名 # print(f2.name) # 遇到异常执行完__exit__就停止且没有再执行此步操作了 # print('******') # 此步操作也没有进行打印 # 且最后会报错 # Traceback (most recent call last): # File "C:/Users/XHP/PycharmProjects/python_quanzhan/s1/day63.py", line 43, in <module> # print(ababab) # 无此变量名 # NameError: name 'ababab' is not defined # class Open_2: # def __init__(self, name): # self.name = name # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_val, exc_tb): # print(exc_type) # <class 'NameError'> 对应异常类 # print(exc_val) # name 'ababab' is not defined 对应异常值 # print(exc_tb) # <traceback object at 0x0000027C6F1A1D40> 对应异常追踪信息 # return True # # with Open_2('c.txt') as f3: # print(ababab) # 无此变量名 # print(f3.name) # 不会打印(__exit__的运行完毕就代表了整个with语句的执行完毕) # print('******') # 会打印(__exit__加入了return True后,还会执行with代码块以外的操作) # 无报错信息