【问题标题】:__repr__ for Exception derived class not works well异常派生类的 __repr__ 效果不佳
【发布时间】:2020-04-25 20:07:59
【问题描述】:

我尝试对从 Exception 继承的对象使用 __repr__ 方法。

但什么都没有打印出来!

谁能帮忙解释一下原因?

class MyException(Exception):
    def __repr__(self):
        return "MyException Object"


try:
    raise MyException()
except MyException as e:
    print(e)   # shows nothing!

【问题讨论】:

    标签: python inheritance exception repr


    【解决方案1】:

    因为MyException 继承了Exception.__str__,这是print 首先咨询的(因为隐式调用是对str(e),如果__str__ 没有,则它只会在内部回退到__repr__存在。

    奇怪的是,Exception.__str__ 返回一个空白字符串:

    >>> str(Exception())
    ''
    

    我想玩弄它,它会返回作为参数传递给 Excpetion 的任何内容

    >>> str(Exception(1))
    '1'
    >>> str(Exception(None))
    'None'
    >>> str(Exception(None, True))
    '(None, True)'
    

    所以改写__str__。或者更好的是,除了:

    class MyException(Exception):
        def __repr__(self):
            return "MyException Object"
        __str__ = __repr__
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 2011-11-13
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多