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

如何仅定义一次__add__方法,解决不同类对象相加的代码冗余?

解决不同类对象相加的代码冗余问题

问题根源

当执行a + b时,Python会先尝试调用a.__add__(b);如果该方法返回NotImplemented(表示无法处理该操作),Python才会转而调用b.__radd__(a)。你当前的写法是每个类都重复实现__add__,导致代码冗余,且后续新增同类结构的类时,还要重复编写相同逻辑。

最优解决方案:基于基类封装通用加法逻辑

创建一个基类,把通用的加法逻辑(包括__add__和__radd__)封装在基类中,所有需要支持相加的子类直接继承这个基类即可,无需重复编写加法相关代码。这种方式不仅消除冗余,还具备良好的扩展性——新增类时只需继承基类,不用额外修改加法逻辑。

代码示例

class Car:
    def __init__(self, no_cars):
        self.no_cars = no_cars
    
    def __add__(self, other):
        # 确保操作数是Car子类实例,具备no_cars属性
        if isinstance(other, Car):
            return self.no_cars + other.no_cars
        return NotImplemented  # 无法处理时返回,触发__radd__
    
    def __radd__(self, other):
        # 复用__add__的逻辑处理反向相加
        return self.__add__(other)

class Ferrari(Car):
    pass  # 继承基类的__init__和加法逻辑,无需重复编写

class Jaquar(Car):
    pass  # 同理继承基类

# 测试两种顺序的相加
f1 = Ferrari(5)
j1 = Jaquar(10)
print(f1 + j1)  # 输出15
print(j1 + f1)  # 输出15

备选方案:单类实现完整加法逻辑,其他类触发反向调用

如果不想使用继承,可以在其中一个类中实现完整的__add__和__radd__,其他类的__add__返回NotImplemented,让Python自动调用反向加法方法。不过这种方式扩展性较差,适合类数量较少的场景:

代码示例

class Ferrari:
    def __init__(self, no_cars):
        self.no_cars = no_cars
    
    def __add__(self, other):
        if hasattr(other, 'no_cars'):
            return self.no_cars + other.no_cars
        return NotImplemented
    
    def __radd__(self, other):
        return self.__add__(other)

class Jaquar:
    def __init__(self, no_cars):
        self.no_cars = no_cars
    
    def __add__(self, other):
        # 不处理,交给对方的__radd__
        return NotImplemented

f1 = Ferrari(5)
j1 = Jaquar(10)
print(f1 + j1)  # 15
print(j1 + f1)  # 15

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:05:21