fromhtml
https://www.pythoncentral.io/what-is-the-difference-between-__str__-and-__repr__-in-python/python
官方解釋:web
object.__repr__(self)
: called by therepr()
built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object.
object.__str__(self)
: called by thestr()
build-in function and by the print statement to compute the "informal" string representation of an object.ideQuote from Python's Data Modelui
二者都是對對象的表述, repr是正式的解釋, str是信息形式的解釋lua
>>> x = 1>>> repr(x)'1'>>> str(x)'1'>>> y = 'a string'>>> repr(y)"'a string'">>> str(y)'a string'
對於整數沒有差異, 對於字符串, 咱們能夠看到差異spa
While the return of
repr()
andstr()
are identical forint x
, you should notice the difference between the return values forstr y
. It is important to realize the default implementation of__repr__
for astr
object can be called as an argument toeval
and the return value would be a validstr
objectcode
repr的返回值能夠被eval再還原回字符串。orm
>>> repr(y)"'a string'">>> y2 = eval(repr(y))>>> y == y2True
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.htm
對於非基本類型的複雜對象, 則不能被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.