关于字符串:python`str()`函数是否调用类的__str__()`函数?

Does python `str()` function call `__str__()` function of a class?

如果我用自己的__str__()函数定义一个类,那么str(a)是否等价于a.__str__(),其中a是我类的一个实例?

我检查了python文档,它没有明确地说明这是事实。


简短回答:是的!

根据python文档(我突出显示了相关部分):

object.__str__(self)

Called by str(object) and the built-in functions format() and print() to compute the"informal" or nicely printable string representation of an object. The return value must be a string object.

This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression: a more convenient or concise representation can be used.

The default implementation defined by the built-in type object calls object.__repr__().

所以当你做str(your_instance)时,通常称为your_instance.__str__

更长的答案:对于"特殊方法"(带有两个前导下划线和两个尾随下划线的方法),有一个异常,因为这些方法是在类上查找的,而不是在实例上查找的。所以str(a)实际上是type(a).__str__(a)而不是a.__str__()。但在大多数情况下,它们是相同的,因为很少有人重写实例上类的方法。尤其是不特殊的方法。

另请参见"特殊方法查找"的相关文档:

For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.

因此,正如@zzh1996在注释中指出的那样,以下代码将使用类上定义的方法,即使实例具有自定义的可调用__str__属性:

1
2
3
4
5
6
7
8
9
>>> class A(object):
...     def __str__(self):
...         return 'a'
>>> instance = A()
>>> instance.__str__ = lambda: 'b'
>>> str(instance)
'a'
>>> instance.__str__()
'b'


是的,是的。请看下面的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> class A:
...     def __init__(self, a):
...         self.a = a
...     def __str__(self):
...         print"Inside __str__"
...         return self.a
...
>>>
>>> a = A('obj1')
>>> a
<__main__.A instance at 0x0000000002605548>
>>>
>>> a.__str__()
Inside __str__
'obj1'
>>>
>>> str(a)
Inside __str__
'obj1'

根据__str__()号文件,我们有:

object.__str__(self)

Called by str(object) and the built-in functions
format() and print() to compute the"informal" or nicely printable
string representation of an object. The return value must be a string
object.


是的,但也在印刷品上。参见文档https://docs.python.org/2/reference/datamodel.html object.str