美文网首页
python: __str__ v.s. __repr__

python: __str__ v.s. __repr__

作者: 庞贝船长 | 来源:发表于2017-12-06 14:36 被阅读0次

__str__ v.s. __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)'
def __repr__(self):
    return '<{0}.{1} object at {2}>'.format(
      self.__module__, type(self).__name__, hex(id(self)))

相关文章

网友评论

      本文标题:python: __str__ v.s. __repr__

      本文链接:https://www.haomeiwen.com/subject/tvakixtx.html