关于这个问题,Stackoverflow已经有了非常好的回答,我认为解释的非常清楚,链接如下:
https://stackoverflow.com/questions/1436703/difference-between-str-and-repr
回答摘要
- The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah)
__repr__
goal is to be unambiguous__str__
goal is to be readable- Container’s
__str__
uses contained objects’__repr__
summary
Implement
__repr__
for any class you implement. This should be second nature. Implement__str__
if you think it would be useful to have a string version which errs on the side of more readability in favor of more ambiguity.