• python的上下文管理协议


    上下文管理协议 with as 语句

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

    enter(self)

    exit(self, exc_type, exc_val, exc_tb)

    enter:出现with语句,对象就会触发__enter__,其返回值会赋给as后的变量名

    exit:with代码执行结束后,会执行__exit__。
    exc_type:异常类型
    exc_val:异常的值
    exc_tb:追溯信息
    注意:
    1、 exit()中的三个参数分别代表异常类型,异常值和追溯信息,with语句中代码块出现异常,则with后的代码都无法执行
    2、 如果 exit()返回值为True,那么异常会被清空,就好像啥都没发生一样,with后的语句正常执行

    用途

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

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

    代码示例

    
    class Open:
        def __init__(self,filepath,mode="r",encode="utf-8"):
            self.f = open(filepath,mode=mode,encoding=encode)
    
        def write(self):
            pass
    
        def __getattr__(self, item):
            return getattr(self.f,item)
    
        def __del__(self):
            print("--->del")
            self.f.close()
    
        def __enter__(self):
            print("出现with语句,对象会调用我")
            return self
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            print("with结束之后,会执行我啦")
            # return True  #返回值为正,with里面抛出异常时,程序不会退出,会执行with代码块,后面的代码
    
    
  • 相关阅读:
    cocos2d-x避免手动修改android.mk文件来编译
    Android.mk详解
    cocos2dx 安卓编译问题收集
    Mac下部署Android开发环境附加NDK
    SpringMVC关于json、xml自动转换的原理研究
    SpringMVC的拦截器
    Spring3中的mvc:interceptors标签配置拦截器
    Spring常用的接口和类(三)
    Spring常用的接口和类(二)
    LeetCode:寻找旋转排序数组中的最小值【153】
  • 原文地址:https://www.cnblogs.com/greatkyle/p/6796991.html
Copyright © 2020-2023  润新知