Discuss / Python / 实现一个简单的with上下文管理对象

实现一个简单的with上下文管理对象

Topic source

ywjco_567

#1 Created at ... [Delete] [Delete and Lock User]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# FileName:with_example.py

class Sample(object):
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print(f'with语句 “{self.name}” 的__enter__被触发....')
        return self

    def __exit__(self, type, value, trace):
        print('with中代码块执行完毕, 进入__exit__....')
        print(f'错误类型: {type} 错误值: {value} 堆栈跟踪: {trace}')
        if trace is None:
            print('执行完成,顺利退出with')
            return True
        else:
            return False  # 返回False,表明方法已完成并且不希望屏蔽引发的异常

    def do_something(self):
        bar = 0
        bar = 1 / 0
        # try:
        #    bar = 1/0
        # except Exception as e:
        #     print(f'捕捉到错误,是 : {e}')      #如果在函数内部拦截错误,错误就不会向外传出
        #     # raise e                    # 但是, 还是可以人为引发

        return bar + 10
if __name__ == '__main__':
    with Sample('我是上下文管理的对象') as s:
        s.do_something()

ywjco_567

#2 Created at ... [Delete] [Delete and Lock User]

运行结果:

D:\Python37\python.exe D:/Python37/Code/with_example.py
Traceback (most recent call last):
with语句 “我是上下文管理的对象” 的__enter__被触发....
  File "D:/Python37/Code/with_example.py", line 35, in <module>
with中代码块执行完毕, 进入__exit__....
    s.do_something()
错误类型: <class 'ZeroDivisionError'> 错误值: division by zero 堆栈跟踪: <traceback object at 0x0000021E08857EC8>
  File "D:/Python37/Code/with_example.py", line 25, in do_something
    bar = 1 / 0
ZeroDivisionError: division by zero

进程已结束,退出代码 1

  • 1

Reply