Python:继承顺序?

Python: The sequence of inheritance?

在下面的示例中,我有 2 个 class 父 initialize/declare 相同的变量。为什么它需要第一个 class 而不是第二个 class?这仅供参考。

class ParentClass:
    one = 'I am the first variable'
    two = 'I am the second variable'
    three = 'I am the thirt variable'


class ParentClass2:
    three = 'I am the third variable'


class ChildClass(ParentClass, ParentClass2):
    two = 'Different Text'
    pass

childObject = ChildClass()
parentObject = ParentClass()

print(parentObject.one)
print(parentObject.two)
print(childObject.one)
print(childObject.two)
print(childObject.three)

输出:

I am the first variable

I am the second variable

I am the first variable

Different Text

I am the thirt variable

因为 ParentClass 在 mro 中排在第一位

 print(ChildClass.__mro__)
(<class '__main__.ChildClass'>, <class '__main__.ParentClass'>, <class '__main__.ParentClass2'>, <class 'object'>)

如果您更改顺序,您将获得预期的输出:

class ChildClass(ParentClass2,ParentClass):

(<class '__main__.ChildClass'>, <class '__main__.ParentClass2'>, <class '__main__.ParentClass'>, <class 'object'>)

Python 从左到右检查属性,因为您首先有 ParentClass,所以您从 ParentClass class

中获取属性