简体   繁体   English

为什么 super() 只调用 class Parent1 的构造函数而不调用 class Parent2 的构造函数?

[英]Why super() is calling constructor of class Parent1 only and not calling constructor of class Parent2?

class Parent1:
    def __init__(self):
        self.data1 = 10
        print("parent1")

class Parent2:
    def __init__(self):
        self.data2 = 20 
        print("parent2")

class child(Parent2,Parent1):
    def __init__(self):
        print("this is child class")
        super().__init__()
        print(self.data1)
        print(self.data2)
        
obj = child()

Output: Output:

this is child class
parent2
Traceback (most recent call last):
  File "f:/Project2020/Rough Work/rough2.py", line 18, in <module>
    obj = child()
  File "f:/Project2020/Rough Work/rough2.py", line 15, in __init__
    print(self.data1)
AttributeError: 'child' object has no attribute 'data1'

Answer to your question: in python there is an inheritance chain.回答您的问题:在 python 中有一个 inheritance 链。 In your case this inheritance chain looks like [Child, Parent2, Parent1],在您的情况下,这个 inheritance 链看起来像 [Child, Parent2, Parent1],
so kinda for the python compiler there's no such thing as multiple inheritance.所以对于 python 编译器来说,没有多个 inheritance 这样的东西。 super() is just a short-hand to walk one step up the inheritance chain. super()只是在 inheritance 链上走一步的捷径。 Therefore your statement is equal to Parent2.__init__() and indeed super().__init__() calls Parent2.__init__() as it should.因此,您的声明等于Parent2.__init__()并且实际上super().__init__()调用Parent2.__init__()应该如此。
So you also need to call Parent1.__init__() from class Child .因此,您还需要从 class Child调用Parent1.__init__()

I suggest writing:我建议写:

class Parent1:
    def __init__(self):
        self.data1 = 10
        print("parent1")

class Parent2:
    def __init__(self):
        self.data2 = 20 
        print("parent2")

class Child(Parent2,Parent1):
    def __init__(self):
        print("this is child class")
        Parent2.__init__(self)
        Parent1.__init__(self)
        print(self.data1)
        print(self.data2)

In this situation the code is clearer if you don't use super() .在这种情况下,如果您不使用super() ,代码会更清晰。 This code may look odd but here using super() would be just confusing anyway.这段代码可能看起来很奇怪,但在这里使用super()无论如何都会令人困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM