Python super().__init__() 具有多重继承

Python super().__init__() with multiple inheritances

class School:
    def __init__(self, school_name):
        self._school = school_name

class Exam:
    def __init__(self, exam_name):
        self._exam_name = exam_name
    def credit(self):
        return 3

class Test(School, Exam):
    def __init__(self, school_name, exam_name):
        self._date = "Oct 7"
        super().__init__(school_name, exam_name)

test = Test('Success', 'Math')
print(test._school) 
print(test._exam_name) 

我只是想知道为什么 super().init() 不能在这里工作。如果我坚持使用 super(),正确的方法是什么才能成功传递 school_name 和 exam_name。

超级函数仅从 MRO 订单调用父 class。据此,您的首选 class 将是 School 并且将调用 School 的 init。在调用 super().__init__(self,school_name) 时,您必须仅提供 school_name 作为参数。但是如果你想调用特定的__init__(),那么最好使用<parent_class>.<method>(<parameters>)。如果你想同时调用这两个初始化函数,尝试这样做:

class School:
    def __init__(self, school_name):
        self._school = school_name

class Exam:
    def __init__(self, exam_name):
        self._exam_name = exam_name
    def credit(self):
        return 3

class Test(School, Exam):
    def __init__(self, school_name, exam_name):
        self._date = "Oct 7"
        School.__init__(self,school_name)
        Exam.__init__(self,exam_name)

test = Test('Success', 'Math')
print(test._school) 
print(test._exam_name)

尝试这样做