gpt4 book ai didi

Python:继承顺序?

转载 作者:行者123 更新时间:2023-11-30 23:14:55 25 4
gpt4 key购买 nike

在下面的示例中,我有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com