Python:继承顺序?

标签 python sequence

在下面的示例中,我有 2 个父类初始化/声明相同的变量。为什么要坐第一个类而不是第二堂课呢?这仅用于知识目的。

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 类获取属性

关于Python:继承顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28514798/

相关文章:

python - 使绘图树状图也显示负值(Python)

python - 获取用于 django 动态过滤器的 url 参数

collections - 如何在 Kotlin 中无限重复序列?

sql 序列计数

python - 主 ID 序列不递增

python - Python 中是否有等同于 Typescript 感叹号的东西?

python - 将 bash 指向安装在 Windows 上的 python

python - 尝试使用for循环找到一种有效的方法来查找python中的所有因素

java - 冰雹序列,递归,缺少 1 个案例

hibernate - 如何使用 Hibernate 中的序列作为 XML 映射中的属性