What is the difference between __str__ and __repr__ in Python

from

https://www.pythoncentral.io/what-is-the-difference-between-__str__-and-__repr__-in-python/

目的

官方解释:

object.__repr__(self): called by the repr() built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object.
object.__str__(self): called by the str() build-in function and by the print statement to compute the "informal" string representation of an object.

Quote from Python's Data Model

两者都是对对象的表述, repr是正式的解释, str是信息形式的解释

基本类型的的默认实现


>>> x = 1
>>> repr(x)
'1'
>>> str(x)
'1'
>>> y = 'a string'
>>> repr(y)
"'a string'"
>>> str(y)
'a string'

      对于整数没有差别, 对于字符串, 我们可以看到差别

While the return of repr() and str() are identical for int x, you should notice the difference between the return values for str y. It is important to realize the default implementation of __repr__ for a str object can be called as an argument to eval and the return value would be a valid str object

      repr的返回值可以被eval再还原回字符串。

>>> repr(y)
"'a string'"
>>> y2 = eval(repr(y))
>>> y == y2
True

复杂对象

Therefore, a "formal" representation of an object should be callable by eval() and return the same object, if possible. If not possible, such as in the case where the object's members are referring itself that leads to infinite circular reference, then __repr__ should be unambiguous and contain as much information as possible.

     对于非基本类型的复杂对象, 则不能被eval计算还原, 这种情况必须遵守 意思清楚的 , 包括信息尽量多的原则。

>>> class ClassB(object):
...     def __init__(self, a=None):
...         self.a = a
...
...     def __repr__(self):
...         return '%s(a=a)' % (self.__class__)
...
 
>>> a = ClassA()
>>> b = ClassB(a=a)
>>> a.b = b
>>> repr(a)
"<class '__main__.ClassA'>(<class '__main__.ClassB'>(a=a))"
>>> repr(b)
"<class '__main__.ClassB'>(a=a)"

内置对象的可读性

The __str__ representation of now looks cleaner and easier to read than the formal representation generated from __repr__. Sometimes, being able to quickly grasp what's stored in an object is valuable to grab the "big" picture of a complex program.

      str更加注重可读性, 一眼就可以获取对象内容,不关注实现的细节。

>>> from datetime import datetime
>>> now = datetime.now()
>>> repr(now)
'datetime.datetime(2013, 2, 5, 4, 43, 11, 673075)'
>>> str(now)
'2013-02-05 04:43:11.673075'

Tips and Suggestions between __str__ and __repr__ in Python

  • Implement __repr__ for every class you implement. There should be no excuse.
  • Implement __str__ for classes which you think readability is more important of non-ambiguity.
原文地址:https://www.cnblogs.com/lightsong/p/10699709.html