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

Python实现双父类多继承时触发TypeError缺失capacity参数如何解决

问题根源

Python多继承遵循**方法解析顺序(MRO)**规则,你定义SuperCargoCar(SuperCar, CargoCar)时,MRO调用链为 SuperCargoCar → SuperCar → CargoCar → Car。你在SuperCargoCar的__init__中调用super().__init__(brand, colour, max_speed)时:

  1. 首先进入SuperCar的__init__方法
  2. SuperCar内部的super().__init__(brand, colour)会按照MRO顺序调用下一个类也就是CargoCar的__init__
  3. 但CargoCar的__init__要求必须传入capacity参数,这里只传了2个参数,就触发了缺失参数的报错。

修复方案

你可以通过两种方式修复问题:

方案1:改造父类支持参数透传(推荐,符合Python多继承设计规范)

给所有父类的初始化方法增加**kwargs参数,透传多余参数给MRO链上的后续类:

class Car:
    def __init__(self, brand, colour, **kwargs):
        self.brand = brand
        self.colour = colour


class SuperCar(Car):
    def __init__(self, brand, colour, max_speed, **kwargs):
        super().__init__(brand, colour, **kwargs)
        self.max_speed = max_speed

    def introduce_yourself(self):
        statement = f"My colour is {self.colour} and my max speed is {self.max_speed}"
        return statement


class CargoCar(Car):
    def __init__(self, brand, colour, capacity, **kwargs):
        super().__init__(brand, colour,** kwargs)
        self.capacity = capacity

    def introduce_yourself(self):
        statement = f"My colour is {self.colour} and my capacity is {self.capacity} KG"
        return statement


class SuperCargoCar(SuperCar, CargoCar):
    def __init__(self, brand, colour, max_speed, capacity):
        super().__init__(brand, colour, max_speed=max_speed, capacity=capacity)

    def introduce_yourself(self):
        statement = f'My colour is {self.colour}, my max speed is {self.max_speed} ' \
                    f'and my capacity is {self.capacity} KG'
        return statement


super_cargo_car = SuperCargoCar(brand="Volvo", colour="Green", max_speed=200, capacity=5000)
print(super_cargo_car.introduce_yourself())

这种写法兼容性强,后续新增父类也不需要大幅调整初始化逻辑。

方案2:显式调用父类初始化(无需修改原有父类代码)

直接在子类中分别显式调用两个父类的初始化方法,跳过super()隐式调用的MRO链式参数传递问题:

class SuperCargoCar(SuperCar, CargoCar):
    def __init__(self, brand, colour, max_speed, capacity ):
        # 显式调用两个父类的初始化方法
        SuperCar.__init__(self, brand, colour, max_speed)
        CargoCar.__init__(self, brand, colour, capacity)

    def introduce_yourself(self):
        statement = f'My colour is {self.colour}, my max speed is {self.max_speed} ' \
                    f'and my capacity is {self.capacity} KG'
        return statement

两种方案运行后都会正常输出:

My colour is Green, my max speed is 200 and my capacity is 5000 KG

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:24:03