python: __str__ v.s. __repr__

__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)))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容