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

Python自定义Celsius类实例相加报TypeError的解决方案

问题根因

Python中重载+运算符对应的特殊方法(魔术方法)要求命名为前后各带两个下划线的__add__,你代码里写的是前后仅单个下划线的_add_,不符合Python运算符重载的方法命名规则,解释器无法识别这个方法为加法运算的实现,因此执行+操作时会抛出TypeError。

修复步骤
  • 将加法方法的名称从_add_修改为__add__
  • (可选)增加入参类型校验,避免传入非Celsius类型对象时出现非预期错误
修复后完整可运行代码
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def __add__(self, other):
        if not isinstance(other, Celsius):
            raise TypeError("加法运算仅支持Celsius类型实例")
        return Celsius(self.temperature + other.temperature)

    @property
    def temperature(self):
        print("Getting value...")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        print("Setting value...")
        self._temperature = value
效果验证

执行预期测试代码:

out = Celsius(37) + Celsius(6)
print("计算得到的温度值:", out.temperature)

运行后输出如下,最终得到的out实例temperature属性值为43,符合预期:

Setting value...
Setting value...
Getting value...
Getting value...
Setting value...
Getting value...
计算得到的温度值: 43

补充说明:如果后续需要支持整数/浮点数 + Celsius实例这类运算顺序反向的场景,只需要额外实现__radd__方法即可,当前两个Celsius实例相加的场景仅修正__add__命名即可满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 13:57:12