Python 多重继承 child(parent1, parent2) access parent2 __init__

Python Multiple Inheritance child(parent1, parent2) access parent2 __init__

假设我有这个 class

class child(parent1, parent2):
    pass

如果 parent1 也定义了 __init__,是否可以访问 parent2.__init__

这是我的完整代码。

class parent1:
    def __init__(self):
        self.color="Blue"

class parent2:
    def __init__(self):
        self.figure="Triangle"

class child(parent1,parent2):
    pass


juan=child()
try:
    print(juan.color)
except Exception as e:
    print(e)
try:
    print(juan.figure)
except Exception as e:
    print(e)

print(juan.__dict__)

我试过

class child(parent1,parent2):
    def __init__(self):
        super(parent2).__init__()

但也许我遗漏了什么?

谢谢。 问候。

parent1parent2,如果希望在协同多重继承设置中使用,应该调用super.

class parent1:
    def __init__(self):
        super().__init__()
        self.color = "Blue"

class parent2:
    def __init__(self):
        super().__init__()
        self.figure = "Triangle"

当你定义child时,它的方法解析顺序决定了哪个__init__先被调用,同时也决定了每次调用哪个class super()被调用。在您的实际示例中,

class child(parent1,parent2):
    pass

parent1.__init__ 首先被调用(因为 child 不会覆盖 __init__),它对 super() 的使用是指 parent2。如果您改为定义

class child2(parent2, parent1):
    pass

parent2.__init__会先被调用,其使用super()会参考parent1.

super() 不是用来确保调用 object.__init__(它什么都不做),而是 object.__init__ 存在以便它 可以super() 调用链结束时调用。 (object.__init__ 本身 使用 super,因为它保证是任何其他 [=47] 的方法解析顺序中的最后一个 class =].)