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

Python中无__add__方法时,能否通过__iadd__实现加法操作?

通过__iadd__复用逻辑实现__add__加法操作

先明确Python操作符的调用规则

  • 当对象有__add__但无__iadd__时:
    • obj = obj + other直接调用obj.__add__(other)生成新对象
    • obj += other会先尝试调用obj.__iadd__,失败则 fallback 到__add__,同样生成新对象后赋值

核心问题解答:可以通过副本+iadd__实现__add

完全可以不用单独编写__add__的逻辑,只需要在__add__方法里创建当前对象的副本,对副本执行__iadd__操作,最后返回这个副本即可。这样既复用了原地修改的逻辑,又能让+操作生成新对象(不修改原对象),同时+=保持原地修改的特性。

用MyInteger类示例演示

反例:只实现__iadd__会导致+操作报错

如果只实现__iadd__,+操作会直接触发TypeError:

class MyInteger:
    def __init__(self, value):
        self.value = value
    
    def __iadd__(self, other):
        if isinstance(other, MyInteger):
            self.value += other.value
        else:
            self.value += other
        return self

# 测试+=正常执行
a = MyInteger(5)
b = MyInteger(3)
a += b
print(a.value)  # 输出8

# 测试+操作报错
# c = a + b  # TypeError: unsupported operand type(s) for +: 'MyInteger' and 'MyInteger'

正确实现:通过副本复用__iadd__实现__add__

添加__add__方法,利用对象副本调用__iadd__:

class MyInteger:
    def __init__(self, value):
        self.value = value
    
    # 实现对象复制方法,用于生成副本
    def copy(self):
        return MyInteger(self.value)
    
    def __iadd__(self, other):
        if isinstance(other, MyInteger):
            self.value += other.value
        else:
            self.value += other
        return self
    
    def __add__(self, other):
        # 创建当前对象的副本
        copy_obj = self.copy()
        # 对副本执行+=操作(实际调用__iadd__)
        copy_obj += other
        # 返回修改后的副本,作为+操作的结果
        return copy_obj

# 测试+操作(生成新对象,不修改原对象)
a = MyInteger(5)
b = MyInteger(3)
c = a + b
print(c.value)  # 输出8
print(a.value)  # 原对象未被修改,输出5

# 测试+=操作(原地修改原对象)
a += b
print(a.value)  # 输出8

扩展到其他操作符

对于-/-=、*/*=、///=、|/|=、&/&=等操作符,都可以套用这个模式:

  1. 先实现原地修改的__ixxx__方法(比如__isub__、__imul__等)
  2. 在对应的__xxx__方法(__sub__、__mul__等)中创建对象副本,调用__ixxx__后返回副本

这样就能统一逻辑,避免重复编写相似的代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:12:53