with open as f: 等同于 f = obj.__enter__()
代码块
with obj-------->触发obj.__enter__(),拿到返回值
as f ----------->f = 返回值
执行代码块:
一:没有异常的情况下,整个代码块运行完毕后去触发__excit__,它的三个参数都为None
二:有异常的情况下,从异常出现的文职直接触发__exit__,
a:如果__exit__的返回值为True,代表吞掉异常
b :如果__exit__的返回值不为True,代表吐出了异常
c:__exit__的运行完毕就代表了整个with语句的执行完毕
1 # f = open('aaa.txt', 'w') # 相当于为open类创建一个实例对象f,此时f实例就加载到内存中 2 # f.close() # 调用close()就可以关闭文件,清理垃圾。 3 class Open: 4 def __init__(self, name): 5 self.name = name 6 7 def __enter__(self): 8 print('执行enter方法') 9 return self 10 11 def __exit__(self, exc_type, exc_val, exc_tb): # exc_type异常信息的类,exc_val异常的值,exc_tb异常的追踪信息 12 print('执行exit方法') # val value tb traceback 13 print(exc_tb) 14 print(exc_type) 15 print(exc_val) 16 # return True # 把异常直接吞掉 17 18 19 # print(Open('s')) 20 with Open('aaa.txt') as f: # with Open('aaa.txt') 触发__enter__方法 21 print(f.name) 22 print('======>') 23 print('======>') 24 print('======>') 25 print(sdkfjklsdjf) 26 print('00000000000000000000000000000') 27 输出: 28 执行enter方法 29 aaa.txt 30 ======> 31 ======> 32 ======> 33 执行exit方法 34 <traceback object at 0x00811EA8> 35 <class 'NameError'> 36 name 'sdkfjklsdjf' is not defined 37 Traceback (most recent call last): 38 File "C:/Users/Administrator/Desktop/python/3月10日/上下文管理协议.py", line 25, in <module> 39 print(sdkfjklsdjf) 40 NameError: name 'sdkfjklsdjf' is not defined