You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多继承中如何用super()实现父类__init__初始化?

多重继承下用super()调用多个父类__init__的实现方法

在Python多重继承场景中,确实可以用super()替代直接调用父类名称的方式来初始化多个父类,以下是两种可行的实现方案:

方案一:修改父类(推荐,符合Python多重继承最佳实践)

原父类A、B、C的__init__既没有调用super(),也不支持参数传递,我们可以调整它们的方法,让每个父类处理自身参数后,通过**kwargs将剩余参数传递给MRO(方法解析顺序)链中的下一个类:

class A:
    def __init__(self, one, **kwargs):
        self.one = one
        super().__init__(**kwargs)

class B:
    def __init__(self, two, **kwargs):
        self.two = two
        super().__init__(**kwargs)

class C:
    def __init__(self, three, **kwargs):
        self.three = three
        super().__init__(**kwargs)

class Text(A, B, C):
    def __init__(self, one, two, three):
        # 一次性传递所有参数,MRO链会自动分发到对应父类
        super().__init__(one=one, two=two, three=three)

    def show_name(self):
        return f"The name is {self.one}{self.two}{self.three}"

the_name = Text("El", "ze", "ro")
print(the_name.show_name())  # 输出:The name is Elzero

方案二:不修改父类(适用于父类不可修改的场景)

如果无法改动A、B、C的代码,可以通过指定super()的第一个参数,跳过前面的父类,直接调用后续父类的__init__:

class A:
    def __init__(self, one):
        self.one = one

class B:
    def __init__(self, two):
        self.two = two

class C:
    def __init__(self, three):
        self.three = three

class Text(A, B, C):
    def __init__(self, one, two, three):
        super().__init__(one)  # 调用MRO链中第一个父类A的__init__
        super(A, self).__init__(two)  # 跳过A,调用MRO链中A之后的B的__init__
        super(B, self).__init__(three)  # 跳过B,调用MRO链中B之后的C的__init__

    def show_name(self):
        return f"The name is {self.one}{self.two}{self.three}"

the_name = Text("El", "ze", "ro")
print(the_name.show_name())  # 输出:The name is Elzero

原理说明

Python多重继承遵循MRO规则,super()默认按MRO顺序调用下一个类的方法。方案一中通过**kwargs传递参数,让每个父类只处理自身需要的参数,剩余参数继续传递;方案二中通过指定super()的第一个参数(父类类型),手动指定MRO链的起始位置,从而逐个调用目标父类的初始化方法。

内容的提问来源于stack exchange,提问作者ProgrammingLearner2023

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 04:06:34