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

Python如何实现__add__方法支持2个以上自定义类实例连续相加?

问题原因

你当前的代码报错是因为__add__方法返回值为字符串类型:

  • 第一次执行car1 + car2时,两个都是Car类实例,调用自定义__add__得到拼接后的字符串
  • 后续执行[字符串] + car3时,会调用Python内置字符串的加法方法,该方法仅支持拼接字符串,无法识别Car类实例,直接抛出类型错误。
解决方法

仅需要在父类Car中调整__add__逻辑,同时新增__radd__反向加法方法,兼容字符串和Car实例相加的场景即可:

  1. __add__判断相加对象的类型,同时支持Car实例和字符串作为相加项
  2. __radd__处理左操作数为字符串的场景,保证连续相加时所有Car实例都能被正确解析
修改后的完整代码
class Car:

    def __init__(self, brand, color, model, year, mileage):
        self.brand = brand
        self.color = color
        self.year = year
        self.model = model
        self.mileage = mileage

    def __str__(self):
        return  f'TYPE: NORMAL CAR\nBrand: {self.brand}\nColor: {self.color}\n'

    def __add__(self, other):
        line = '- ' * 15
        self_block = '\n'.join([str(self), self.documentation(), line])
        if isinstance(other, Car):
            other_block = '\n'.join([str(other), other.documentation(), line])
            return self_block + '\n' + other_block
        elif isinstance(other, str):
            return self_block + '\n' + other
        else:
            raise TypeError(f"不支持与{type(other)}类型的对象执行加法操作")

    def __radd__(self, other):
        line = '- ' * 15
        self_block = '\n'.join([str(self), self.documentation(), line])
        if isinstance(other, str):
            return other + '\n' + self_block
        else:
            raise TypeError(f"不支持与{type(other)}类型的对象执行加法操作")

    def documentation(self):
        return f'DOCUMENTATION\nModel: {self.model}\nYear: {self.year}\nMileage: {self.mileage} Km'


class SportCar(Car):

    def __init__(self, brand, color, model, year, mileage, engine, maxspeed):
        super().__init__(brand, color, model, year, mileage)
        self.engine = engine
        self.maxspeed = maxspeed

    def __str__(self):
        return  f'TYPE: SPORT CAR\nBrand: {self.brand}\nColor: {self.color}\n'

    def documentation(self):
        return f'DOCUMENTATION\nModel: {self.model}\nYear: {self.year}\nMileage: {self.mileage} Km\nEngine: {self.engine}\nMax Speed: {self.maxspeed}'


car1 = SportCar('Audi', 'Black', 'R8', '2018', '35 000', 'V6', '350 Km/h')
car2 = Car('Skoda', 'White', 'Superb', '2015', '165 000')
car3 = Car('Honda', 'Blue', 'Civic', '2017', '220 000')
car4 = SportCar('BMW', 'Red', 'M5', '2020', '10 000', 'V8', '430 Km/h')

print(car1 + car2 + car3 + car4)

修改后执行print(car1 + car2 + car3 + car4)即可正常输出4个实例的完整信息,也支持任意数量Car实例的连续相加。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 23:09:03