我尝试对__repr__
继承自Exception的对象使用方法。
但是什么也没印出来!
谁能帮忙解释原因?
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__
返回一个空白字符串:
>>> 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__
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句