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

Python中int与Currency类对象相加报错的解决方案咨询

解决int与自定义Currency类双向加法的问题

这个问题的核心在于Python处理二元运算符的顺序:

  • 当执行Currency(1) + 1时,Python会调用Currency实例的__add__方法,你的代码里通过类型转换逻辑把int转成了Currency对象,所以能正常运行。
  • 但执行1 + Currency(1)时,Python会先尝试调用int的__add__方法,而int类根本不知道怎么和Currency对象相加,所以抛出TypeError。

要解决这个问题,你只需要在Currency类中实现__radd__方法——这个方法专门处理右操作数是当前类实例,左操作数不支持加法的场景。同时,我们还需要修正原代码里类型转换的逻辑错误,让整个加法逻辑更严谨。

修改后的完整代码

class Currency:
    "A general currency class"
    def __init__(self, kr=0, ore=0):
        "Input kr and ore, with default values 0"
        # 统一转换为ore存储,避免浮点精度问题
        total_ore = round(ore + (kr * 100), 0)
        self.kr = int(total_ore // 100)
        self.ore = int(total_ore % 100)

    def __add__(self, other):
        # 先统一类型
        other = self._check_and_convert(other)
        total_ore = self.ore + other.ore
        return Currency(kr=0, ore=total_ore)

    def __radd__(self, other):
        # 加法满足交换律,直接复用__add__的逻辑
        return self.__add__(other)

    def _check_and_convert(self, other):
        # 把int/float转成Currency对象,其他类型抛出明确错误
        if isinstance(other, (int, float)):
            return Currency(kr=other)
        elif not isinstance(other, Currency):
            raise TypeError(f"Unsupported operand type: {type(other)}")
        return other

    def __str__(self):
        return f"{self.kr} kr, {self.ore} ore"

# 测试验证
x = 100
y = Currency(1)
print(y + x)  # 输出: 101 kr, 0 ore
print(x + y)  # 输出: 101 kr, 0 ore

关键修改说明

  1. 实现__radd__方法:
    这个方法会在int.__add__无法处理Currency对象时被触发,我们直接让它调用__add__——因为加法满足交换律,这样a + b和b + a的逻辑完全一致,无需重复写代码。

  2. 优化类型转换逻辑:
    原__check_type方法存在逻辑错误(比如type(int) != Currency是完全错误的判断),我们改成_check_and_convert,只处理int/float到Currency的转换,其他不支持的类型直接抛出明确的错误提示,让代码更健壮。

  3. 修复初始化与字符串输出:
    初始化方法里用整数除法和取模替代浮点运算,避免精度问题;同时实现了__str__方法,让打印实例时能输出友好的格式,而不是默认的内存地址。

这样修改后,不管是Currency + int还是int + Currency都能正常运行了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:37:40