python-3.x - 具有多重继承的 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。
解决方案
超级函数仅从 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)
尝试这样做
推荐阅读
- javascript - 如何让我的开始和停止按钮使用 javascript 工作?
- javascript - 在特定时间后运行一次任务 - 节点 js
- android - 当用户进入地理围栏或居住在地理围栏内时,应用程序意外关闭
- javascript - 用户单击选定按钮时显示详细信息
- powerbi - 隐藏和取消选择“启用加载”有什么区别?
- flutter - 在 Flutter 的屏幕之间传递 Hive 框
- android - 视图ID的整数值在android中是否始终不变?
- machine-learning - 使用具有多个自变量的分类模型进行预测
- laravel - Bangla 字体显示不匹配 - Laravel Dompdf
- ruby - 得到这个'未定义的方法'获取''