__str__ v.s. __repr__
- 具体阅读 stackoverflow上的问题: Difference between str and repr in Python
对应 Top 1 回答的翻译: Python 中 str 和 repr 的区别
做几点摘要:
-
My rule of thumb:
__repr__
is for developers,__str__
is for customers. -
Note that there is one default which is true: if
__repr__
is defined, and__str__
is not, the object will behave as though__str__=__repr__
>>> class Sic(object): pass
...
>>> print str(Sic())
<__main__.Sic object at 0x8b7d0>
>>> print repr(Sic())
<__main__.Sic object at 0x8b7d0>
>>>
>>> class Sic(object):
... def __repr__(object): return 'foo'
...
>>> print str(Sic())
foo
>>> print repr(Sic())
foo
>>> class Sic(object):
... def __str__(object): return 'foo'
...
>>> print str(Sic())
foo
>>> print repr(Sic())
<__main__.Sic object at 0x2617f0>
- In short, the goal of
__repr__
is to be unambiguous and__str__
is to be readable.
>>> import datetime
>>>
>>> now = datetime.datetime.now()
>>> str(now)
'2017-12-06 14:42:27.403028'
>>> repr(now)
'datetime.datetime(2017, 12, 6, 14, 42, 27, 403028)'
- The default object
__repr__
is (C Python source) something like:
def __repr__(self):
return '<{0}.{1} object at {2}>'.format(
self.__module__, type(self).__name__, hex(id(self)))
网友评论