且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python`str()`函数调用类的`__str __()`函数吗?

更新时间:2023-10-21 23:47:52

简短答案:是!




根据 Python文档(我突出了相关部分):


object .__ str __(self)


str(object)和内置函数format()和print()调用,以计算对象的非正式或可很好打印的字符串表示形式。返回值必须是字符串对象。


此方法与 object .__ repr __()不同,因为我们不希望 __ str __()返回有效的Python表达式:可以使用更方便或更简洁的表示形式。


类型对象调用 object .__ repr __()


所以 your_instance .__ str __ 通常在您执行 str(您的实例)时调用。




str(a)实际上是 type(a).__ str __(a)而不是 a .__ str __()。但是在大多数情况下,它们是相同的,因为很少会在实例上覆盖类的方法。特别是不是特殊的方法。

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


对于自定义类,隐式调用只有在对象的类型上定义了特殊方法,才能保证它们正确工作,而在对象的实例字典中没有定义。


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

 >> A类(对象):
... def __str __(自我):
...返回 a
>>>实例= A()
>> instance .__ str__ = lambda:‘b’
>>> str(instance)
‘a’
>>> instance .__ str __()
’b’


If I define a class with its own __str__() function, is str(a) equivalent to a.__str__(), where a is an instance of my class?

I checked the python doc, it doesn't say explicitly that this is the case.

Short answer: Yes!


According to the Python docs (I highlighted the relevant part):

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__().

So your_instance.__str__ is generally called when you do str(your_instance).


Longer answer: With "Special Methods" (the methods with two leading underscores and two trailing underscores) there is an exception because these are looked up on the class, not the instance. So str(a) is actually type(a).__str__(a) and not a.__str__(). But in most cases these are the same, because one rarely overrides methods of the class on the instance. Especially not special methods.

See also the relevant documentation on "Special method lookup":

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.

So like @zzh1996 pointed out in the comments the following code will use the method defined on the class even though the instance has a custom callable __str__ attribute:

>>> class A(object):
...     def __str__(self):
...         return 'a'
>>> instance = A()
>>> instance.__str__ = lambda: 'b'
>>> str(instance)
'a'
>>> instance.__str__()
'b'