str() 不会根据 MRO 返回“{}”

问题描述 投票:0回答:1

对于继承自 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>
python dictionary multiple-inheritance
1个回答
0
投票

dict.__str__
是在
object
中实现的,而不是
dict
中。 (实现基本上是
return repr(self)
- 它不是
dict
特定的。)

dict

 中,
A
可能出现在
B.__mro__
之前,但
A
出现在
object
之前,因此
A
__str__
实现先于
object
的实现找到。

© www.soinside.com 2019 - 2024. All rights reserved.