python 上下文管理协议
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 用途或者说好处: 1.使用with语句的目的就是把代码块放入with中执行,with结束后,自动完成清理工作,无须手动干预 2.在需要管理一些资源比如文件,网络连接和锁的编程环境中,可以在__exit__中定制自动释放资源的机制,你无须再去关系这个问题,这将大有用处
相关推荐
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