class MyException(Exception):
def __init__(self, line, file):
self.line = line
self.file = file
def __repr__(self):
return "line:{0},file:{1}".format(self.line, self.file)
exp = MyException(12, "text.log")
print(exp) # 不会输出:line:12,file:text.log,而是输出了(12,"text.log")
print(repr(exp)) 输出了(12,"text.log")
Exception
这个基类自带一个 __str__
实现,它会把构造时传进去的所有参数原样打包成元组后转成字符串。
因此 print(exp)
会优先找到这个内置的 __str__
,而不是你写的 __repr__
。
验证:print(MyException.__str__ is BaseException.__str__) # True
也就是说,只要你不覆盖 __str__
,Exception
就永远用自己的版本。__str__优先级比__repr__优先级高
print(exp)
也显示你定义的格式,要么:__str__
(最简单)