python 上下文管理协议

idning 2020-01-12

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__中定制自动释放资源的机制,你无须再去关系这个问题,这将大有用处

相关推荐