什么是上下文管理协议

上下文管理协议其实就是with Foo() as f:类似这种写法

class Foo:
    def __init__(self,name):
        self.name=name
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit')
        print(exc_type)
        print(exc_val)
        print(exc_tb)
        return True

with Foo('a.txt') as f:
    print('ok')
print('-----------end----------')

用with这种写法的最大好处就是不用写f.close()了。

posted @   疯狂Python  阅读(2)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示