zoukankan      html  css  js  c++  java
  • 20191125:Python中的上下文管理机制with

    20191125:with上下文管理

    with是一个上下文管理器,用于执行代码块所需要的运行的时候的上下文入口和出口。上下文管理器的典型用法包括保存和还原各种全局状态,锁定和解锁资源,关闭打开的文件等。

    先执行__enter__方法,再执行__exit__方法,当对象被实例化时,就会主动调用__enter__()方法,任务执行完成后就会调用__exit__()方法。

    # encoding: utf-8
    class mywith:
        def __enter__(self):
            print("mywith enter方法")
            return self
        def __exit__(self, exc_type, exc_val, exc_tb):
            print("mywith exit方法")
            print("exc_type",exc_type)
            print("exc_val",exc_val)
            print("exc_tb",exc_tb)
        def tell(self):
            print("tell方法")
    if __name__ == '__main__':
        with mywith() as b:
            b.tell()

    mywith enter方法

    tell方法

    mywith exit方法

    exc_type None

    exc_val None

    exc_tb None

    __exit__()方法是带有三个参数的(exc_type, exc_value, traceback),如果上下文运行时没有异常发生,那么三个参数都将置为None

    如果有异常的情况下执行如下:

    class mywith:
        def __enter__(self):
            print("mywith enter方法")
            return self
        def __exit__(self, exc_type, exc_val, exc_tb):
            print("mywith exit方法")
            print("exc_type",exc_type)
            print("exc_val",exc_val)
            print("exc_tb",exc_tb)
        # def tell(self):
        #     print("tell
    方法")
    if __name__ == '__main__':
        with mywith() as b:
            b.tell()

    mywith enter方法

    mywith exit方法

    exc_type <class 'AttributeError'>

    exc_val 'mywith' object has no attribute 'tell'

    exc_tb <traceback object at 0x00000230DA074C48>

    有异常的时候,exc_type输出异常类型,exc_val输出异常的错误信息,exc_tb输出错误的堆栈对象。因此我们可以在__exit__方法中定义异常的处理如下:

    if exc_type==AttributeError:
        print("AttributeError被处理")

        return True

    Tips:!!如果有异常发生,并且该方法希望抑制异常(即阻止它被传播),则它应该返回True,否则,异常将在退出该方法时正常处理。

  • 相关阅读:
    推荐几款极简的手机浏览器
    const关键字到底该怎么用
    让你的代码更加优雅的编程技巧-跳转表
    Linux中删除特殊名称文件的多种方式
    mybatis Invalid bound statement (not found)错误解决办法
    Maven 上传文件 Error creating bean with name 'multipartResolver':
    Maven Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
    JS 获取json key和value
    spring 注释
    HttpServletRequest 对文件上传的支持
  • 原文地址:https://www.cnblogs.com/hyj691001/p/11930692.html
Copyright © 2011-2022 走看看