__repr__ 对于派生的异常 class 效果不佳

__repr__ for Exception derived class not works well

我尝试在继承自 Exception 的对象上使用 __repr__ 方法。

但没有打印任何内容!

谁能帮忙解释一下为什么?

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


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

因为MyException继承了Exception.__str__,这是print首先查询的内容(因为隐式调用是str(e),它只会在内部回落到__repr__ 如果 __str__ 不存在。

奇怪的是,Exception.__str__ returns 一个空字符串:

>>> str(Exception())
''

我想玩玩它,它 returns 任何作为参数传递给 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__