作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试在继承自 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)
,如果 __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__
关于python - 异常派生类的 __repr__ 效果不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59643308/
我是一名优秀的程序员,十分优秀!