首页 新闻 会员 周边 捐助

怎么没有调用__repr__

0
[已关闭问题] 关闭于 2025-08-29 11:40
复制代码

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")
复制代码
_java_python的主页 _java_python | 小虾三级 | 园豆:984
提问于:2025-08-29 11:15
< >
分享
所有回答(1)
0

Exception 这个基类自带一个 __str__ 实现,它会把构造时传进去的所有参数原样打包成元组后转成字符串。
因此 print(exp) 会优先找到这个内置的 __str__,而不是你写的 __repr__

验证:print(MyException.__str__ is BaseException.__str__) # True

也就是说,只要你不覆盖 __str__Exception 就永远用自己的版本。__str__优先级比__repr__优先级高

想让 print(exp) 也显示你定义的格式,要么:
  1. 同时实现 __str__(最简单)
  2. 或者显示用repr函数,显式调用__repr__
_java_python | 园豆:984 (小虾三级) | 2025-08-29 11:40
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册