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

Python多继承使用super()为何无法调用所有父类的__init__方法

问题原因分析

核心问题是你对super()的作用理解有误,Python中super(type, instance)的作用不是直接调用type类的父类方法,而是从实例对应的方法解析顺序(MRO)列表中,找到排在type类之后的第一个类,再调用该类的对应方法。

首先我们可以先打印happystate类的MRO顺序验证:

print(happystate.__mro__)
# 输出结果为:
# (<class '__main__.happystate'>, <class '__main__.state'>, <class '__main__.event'>, <class 'object'>)

对应你写的两行super调用逻辑:

  • 第一行super(state,self).__init__():从MRO列表中找排在state之后的第一个类,也就是event,所以这行实际调用的是event的__init__方法,输出了in the event class
  • 第二行super(event,self).__init__():从MRO列表中找排在event之后的第一个类是根类object,object的__init__方法无打印逻辑,所以没有额外输出

你全程没有编写调用state类__init__的有效代码,自然不会触发对应的打印输出。

修复方案

如果要依次调用两个父类的初始化方法,有两种常用实现方式:

方式1:显式调用父类方法

直接指定父类名调用,逻辑最直观:

class happystate(state,event):
    def __init__(self):
        print('in the happy state class')
        state.__init__(self)
        event.__init__(self)

方式2:修正super用法,配合父类添加super调用

如果要使用super的多继承协作逻辑,需要每个父类的初始化方法都添加super调用:

class state():
    def __init__(self):
        print('in the state class')
        self.state = "main state"
        super().__init__()

class event():
    def __init__(self):
        print("in the event class")
        self.event = "main event"
        super().__init__()

class happystate(state,event):
    def __init__(self):
        print('in the happy state class')
        super().__init__()

两种修改方式运行happystate()实例化时,都会依次打印三个类的初始化输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:09:00