首页 > 编程语言 > 详细

20191125:Python中的上下文管理机制with

时间:2019-11-25 22:17:22      阅读:110      评论:0      收藏:0      [点我收藏+]

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,否则,异常将在退出该方法时正常处理。

20191125:Python中的上下文管理机制with

原文:https://www.cnblogs.com/hyj691001/p/11930692.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!