__repr__
__repr__在Python文档中这样描述:“Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object.”
__str__
__str__在python文档中的描述如下”Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from repr() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.”
__repr__和__str__的区别
官方文档中str()中描述了__repr__和__str__的区别:”Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ”.”,也就是__str__和__repr__区别在于__str__目的不在于总是尝试返回一个适用于eval()的字符串,而是返回一个很好地向人描述对象的字符串。而__repr__目的在于”makes an attempt to return a string that would yield an object with the same value when passed to eval()”,尝试让返回的字符串能够通过eval()来生成一个一样的对象。
__repr__和__str__的区别在stackoverflow上的回答。大意就是如果实现了__repr__而没有定义__str__,那么对象将会表现出__str__ = __repr__,测试如下:
In [1]: class test1(object):
def __init__(self):
self.a = 1
self.b = 2
def __repr__(self):
return '%s %s %s' % (self.__class__.__name__, self.a, self.b)
In [2]: str(test1())
Out[2]: 'test1 1 2'
In [3]: repr(test1())
Out[3]: 'test1 1 2'
In [20]: class test2(object):
....: def __init__(self):
....: self.a = 1
....: self.b = 2
....: def __str__(self):
....: return '%s %s %s' % (self.__class__.__name__, self.a, self.b)
....:
In [21]: str(test2())
Out[21]: 'test2 1 2'
In [22]: repr(test2())
Out[22]: '<__main__.test2 object at 0x10537c490>'
可以看出没有__str__的情况下确实是在str()方法中会表现出使用了__repr__,反之则不会。所以__str__的实现其实是可选的,如果需要一个容易看懂的打印对象的功能可以实现__str__。
高票回答者喜欢时候%r而不是%s来获取对象的信息(But you have to do the last step — make sure every object you implement has a useful repr, so code like that can just work. This is why the “eval” thing comes up: if you have enough information so eval(repr(c))==c, that means you know everything there is to know about c. )
In [23]: print '%r' % (test1())
test1 1 2
In [24]: print '%r' % (test2())
<__main__.test2 object at 0x10537c390>
__repr__的实现示例
Python的collections中Counter源码中对__repr__实现如下:
def __repr__(self):
if not self:
return '%s()' % self.__class__.__name__
items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
return '%s({%s})' % (self.__class__.__name__, items)
如果没有对象就返回类的名字,否则返回类的名字并且返回利用Counter的most_common()方法得到对象中已有的信息。