对于继承自 dict 的类,当 dict 在类的 MRO 中较早时,为什么 str() 不使用
dict.__str__
?
Python 3.10.12 (main, Sep 11 2024, 15:47:36) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... def __str__(self):
... return "A"
...
>>> class B(dict, A):
... pass
...
>>> B.__mro__
(<class '__main__.B'>, <class 'dict'>, <class '__main__.A'>, <class 'object'>)
>>> str(B())
'A'
>>> str(dict())
'{}'
>>>
调用 str(B()) 时,为什么不优先调用
dict.__str__
而不是 A.__str__
?
它是否与具有 slot_wrapper 而不是函数的 dict 有关?
>>> dict.__str__
<slot wrapper '__str__' of 'object' objects>
>>> A.__str__
<function A.__str__ at 0x75be4ea8a0e0>
>>> B.__str__
<function A.__str__ at 0x75be4ea8a0e0>
dict.__str__
是在 object
中实现的,而不是 dict
中。 (实现基本上是return repr(self)
- 它不是dict
特定的。)
在 dict
中,
A
可能出现在 B.__mro__
之前,但 A
出现在 object
之前,因此 A
的 __str__
实现先于 object
的实现找到。