FreezeJ' Blog

python上下文管理器

2021-12-10

在类里面实现__enter____exit__方法,用于实现上下文管理:

class Manage(object):
    def __init__(self):
        print('init')

    def __enter__(self):
        print('enter')
        return self

    def __exit__(self, exception_type, exception_value, exception_trace):
        print('exception_type:', exception_type)  # 异常类型
        print('exception_value:', exception_value)  # 异常信息
        print('exception_trace:', exception_trace)  # 异常堆栈对象
        print('exit')

    def run(self):
        print('run')


try:
    with Manage() as t:
        t.run()
        raise BaseException('手动触发异常')  # 触发异常
except BaseException:
    print('处理BaseException')

输出结果:

init
enter
run
exception_type: <class 'BaseException'>
exception_value: 手动触发异常
exception_trace: <traceback object at 0x7fbf95f8c448>
exit
处理BaseException