with 上下文协议

上下文管理协议,即with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明__enter__和__exit__方法

class Open:
    def __init__(self,filepath,mode='r',encoding='utf-8'):
        self.filepath=filepath
        self.mode=mode
        self.encoding=encoding
    def __enter__(self):
        self.f=open(self.filepath,mode=self.mode,encoding=self.encoding)
        return self.f
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("finish")
        self.f.close()
        return True      #with执行时发生异常不处理
        # return False
    def __getattr__(self, item):
        return getattr(self.f,item)

with Open('a.txt','w') as f:
    f.write("hahhha")
    # raise AttributeError
    f.asfsd  #return True 时不会报错
print("yam,ahaha")

默认情况:__exit__()中的三个参数分别代表异常类型,异常值和追溯信息,with语句中代码块出现异常,
则with后的代码都无法执行

用途:

1.使用with语句的目的就是把代码块放入with中执行,with结束后,自动完成清理工作,无须手动干预

2.在需要管理一些资源比如文件,网络连接和锁的编程环境中,可以在__exit__中定制自动释放资源的机制,你无须再去关系这个问题,这将大有用处

猜你喜欢

转载自www.cnblogs.com/wuxi9864/p/9967881.html