首页 > 解决方案 > 具有多重继承的 Python super().__init__()

问题描述

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。

标签: python-3.xclassmultiple-inheritance

解决方案


超级函数仅从 MRO 顺序调用父类。根据这一点,您的首选课程将是 School 并且将调用 School 的 init。您必须在调用时只提供 school_name 作为参数super().__init__(self,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)

尝试这样做


推荐阅读