Difference between __str__ and __repr__ in Python

在 Python 里,__str__ 和 __repr__ 的功能类似,但又有区别,经常容易搞混。以下列举了它们在使用上的注意点。

__repr__

  • __repr__ goal is to be unambiguous
  • __repr__ is for developers
  • __repr__ representation of python object usually eval will convert it back to that object
  • 正式的字符串,多数情况下是一个有效的 python 表达式,用于 repr()

__str__

  • __str__ goal is to be readable
  • __str__ is for customers
  • __str__ is whatever you think is that object in text form
  • 非正式的字符串,用于 print()
  • 如果 __str__ 没有定义,__str__ = __repr__

这里有几个描述,可以参考:

Read More: