【Python学习之旅】---上下文管理协议
# with obj as f:# ‘代码块‘## 1.# with obj - ---》触发obj.__enter__(), 拿到返回值## 2.as f - ---->f = 返回值、## 3.# with obj as f 等同于 f=obj.__enter__()## 4.# 执行代码块# 一:没有异常的情况下,整个代码块运行完毕后去触发__exit__, 它的三个参数都为None# 二:有异常的情况下,从异常出现的位置直接触发__exit__# a:如果__exit__的返回值为True,代表吞掉了异常,后面的代码可以继续运行# b:如果__exit__的返回值不为True,代表吐出了异常,后面的代码统统不执行# c:__exit__的的运行完毕就代表了整个with语句的执行完毕class Open: 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_type) print(exc_val) print(exc_tb) return Truewith Open(‘a.txt‘) as f: #执行with open会触发__enter__,返回的self赋值给f print(f) print(frggggffgfg) #如果运行不存在的属性,直接触发__exit__运行,如果有返回True,异常直接被吞掉 print(f.name)print(‘000000000000000000000000‘) #继续运行#执行结果:
执行enter
<__main__.Open object at 0x0000016A045F7A58>
执行exit
<class ‘NameError‘>
name ‘frggggffgfg‘ is not defined
<traceback object at 0x0000016A04613388>
000000000000000000000000
相关推荐
wpfeitian 2020-09-28
wangrui0 2020-07-05
qiximiao 2020-07-05
CSSEIKOCS 2020-06-25
邓博学习笔记 2020-06-15
fenxinzi 2020-06-15
bluecarrot 2020-06-15
onlykg 2020-06-14
cwgxiaoguizi 2020-06-14
atb 2020-06-14
Attend 2020-06-14
咏月东南 2020-06-14
citic 2020-06-14
NeverAgain 2020-06-14
heheeheh 2020-06-14
hickwu 2020-06-14
pointfish 2020-06-14
YoungkingWang 2020-06-13