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

Python类多继承中super()行为疑问与多祖父母类实现咨询

关于Python中super()函数的多继承疑问解答

先看你定义的基类和子类代码:

class Human:
    def __init__(self, name):
        print(name, "is a human")

class Ghost:
    def __init__(self, name):
        print(name, "is a ghost")

# Child of Human class
class Run(Human):
    def __init__(self, name):
        print(name, "can run")
        super().__init__(name)

# Child of Human class
class Whisper(Human):
    def __init__(self, name):
        print(name, "can whisper")
        super().__init__(name)

# Child of Ghost class
class Fly(Ghost):
    def __init__(self, name):
        print(name, "can fly")
        super().__init__(name)

场景1:继承Run和Whisper的Robot

class Robot(Run, Whisper):
    def __init__(self):
        print("I am Robot")
        super().__init__('Robot')

运行结果:

>>> r = Robot()
I am Robot
Robot can run
Robot can whisper
Robot is a human

场景2:继承Run和Fly的Robot

class Robot(Run, Fly):
    def __init__(self):
        print("I am Robot")
        super().__init__('Robot')

运行结果:

>>> r = Robot()
I am Robot
Robot can run
Robot is a human

疑问解答

1. 第一种场景中,Human类的print语句为何只执行一次,而Run和Whisper类中都调用了super()?

Python里的super()不是直接调用父类方法,而是按照当前类的**MRO(方法解析顺序)**调用链中的下一个类的方法。

Robot(Run, Whisper)的MRO顺序是:Robot -> Run -> Whisper -> Human -> object。

调用流程:

  • Robot.__init__调用super().__init__('Robot'),实际执行Run.__init__
  • Run.__init__打印后调用super().__init__(name),此时MRO链中Run的下一个是Whisper,所以执行Whisper.__init__
  • Whisper.__init__打印后调用super().__init__(name),链中下一个是Human,执行Human.__init__
  • Human.__init__打印后没有调用super()(它的父类是object,object的__init__默认无操作),链到此结束

整个MRO链只会走到Human一次,所以它的print语句只执行一次。

2. 第二种场景中,为何Run和Human的方法被成功调用,而Fly和Ghost的方法未被触发?

Robot(Run, Fly)的MRO顺序是:Robot -> Run -> Human -> Fly -> Ghost -> object。

调用流程:

  • Robot.__init__调用super().__init__('Robot'),执行Run.__init__
  • Run.__init__打印后调用super().__init__(name),链中下一个是Human,执行Human.__init__
  • Human.__init__打印后没有调用super(),直接中断了整个调用链,后面的Fly和Ghost自然不会被触发

如果想让Fly和Ghost的方法也执行,需要给Human的__init__加上super().__init__()(哪怕object的__init__没实际操作,也能让链继续走下去)。

3. 是否可以在单个Python类中使用多个不同的祖父母类?

完全可以,Python原生支持多继承,单个类可以同时继承多个类,这些类也可以拥有不同的父类(也就是你说的祖父母类)。但要注意两点:

  • 必须理解MRO顺序,它决定了方法的调用优先级
  • 如果需要所有父类的方法都被执行,每个类的方法都要正确调用super(),保证调用链不中断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:24:47