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

如何在Python中让__iadd__方法同时支持整数与同类对象输入?

实现支持两种输入的__iadd__方法

可以通过在__iadd__方法中判断输入参数的类型,分别处理整数和Data对象两种情况,实现逻辑合并,完整代码示例如下:

class Data:
    def __init__(self, n=0, s=0):
        self.n = n
        self.s = s

    def __iadd__(self, other):
        # 处理整数输入的情况
        if isinstance(other, int):
            self.n += 1
            self.s += other
        # 处理Data对象输入的情况
        elif isinstance(other, Data):
            self.n += other.n
            self.s += other.s
        # 可选:对不支持的类型抛出异常,避免逻辑混乱
        else:
            raise TypeError(f"不支持与{type(other)}类型执行+=操作")
        return self

代码说明

  • 用isinstance()函数判断参数other的类型,区分两种输入场景
  • 整数输入时:执行n自增1、s累加整数的逻辑
  • Data对象输入时:将两个对象的n和s属性分别相加
  • 可选添加异常处理,拦截不支持的输入类型,提升代码健壮性

测试示例

# 测试整数加法
d1 = Data(n=1, s=10)
d1 += 5
print(d1.n, d1.s)  # 输出:2 15

# 测试Data对象合并
d2 = Data(n=3, s=20)
d1 += d2
print(d1.n, d1.s)  # 输出:5 35

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:15:38