Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么super()只调用Parent1类的构造函数而不调用Parent2类的构造函数?_Python_Inheritance_Parent Child_Super_Base Class - Fatal编程技术网

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

Python 为什么super()只调用Parent1类的构造函数而不调用Parent2类的构造函数?,python,inheritance,parent-child,super,base-class,Python,Inheritance,Parent Child,Super,Base Class,输出: 这是子类 父母2 回溯(最近一次呼叫最后一次): 文件“f:/Project2020/Rough Work/rough2.py”,第18行,在 obj=child() 文件“f:/Project2020/Rough-Work/rough2.py”,第15行,在__ 打印(self.data1) AttributeError:“child”对象没有属性“data1” 回答您的问题:python中有一个继承链。在您的例子中,此继承链类似于[Child,Parent2,Parent1], 对于

输出:

这是子类
父母2
回溯(最近一次呼叫最后一次):
文件“f:/Project2020/Rough Work/rough2.py”,第18行,在
obj=child()
文件“f:/Project2020/Rough-Work/rough2.py”,第15行,在__
打印(self.data1)
AttributeError:“child”对象没有属性“data1”

回答您的问题:python中有一个继承链。在您的例子中,此继承链类似于[Child,Parent2,Parent1],
对于python编译器来说,没有多重继承
super()
只是在继承链上迈出一步的捷径。因此,您的语句等于
Parent2.\uuu init\uu()
并且实际上
super()。\uuu init\uu()
调用
Parent2.\uu init\uu()
因此,您还需要从类
Child
调用
Parent1.\uuu init\uuu()

我建议写:

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()

在这种情况下,如果不使用
super()
,代码会更清晰。这段代码可能看起来很奇怪,但在这里使用
super()
无论如何都会让人困惑。

Parent2.\uuuu init\uuuuu
不调用
super()。\uuuu init\uuuuuu
,因此
Parent1.\uuu init\uuuuuu
不会被调用。当您设计多重继承时,所有类都需要在其方法中调用超级实现。为什么super()。\uuuuu init\uuuuu()不调用Parent2类的\uuuuu init\uuuuu()?您的方法非常好。super()是否只调用第一个父类init?我对你的答案很满意。你能帮我解决这个问题吗。它还基于super()和多重继承。谢谢。我看我无法回答你的问题,因为人们把它关闭了。(所以,我在这里回答,如果有帮助,请在这里加上a+1)。因此,由于您的对象具有继承链[Class4,Class2,Class3,Class1],super()将遍历该链,而不是您自然期望的相应类的链。事实上,您甚至可以调用
Class2.m(my_object)
,然后
super()
将遍历
my_object
-s链,可能输出一些更奇怪的东西。我的问题是-。请看。
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)