You need to enable JavaScript to run this app. Python自定义Money类加法运算报int转换ValueError错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python自定义Money类加法运算报int转换ValueError错误如何解决

问题根因

  • 核心错误出在__radd__方法的返回值设计:你当前实现返回的是格式化后的金额字符串,而非Money实例。当执行链式加法10 + m1 + m2时,第一步10 + m1运算结束后得到的是类似$13.50的字符串,第二步执行「字符串 + m2」时会触发m2的__radd__方法,此时入参other是字符串,你的类型判断逻辑没有覆盖字符串场景,直接执行int(other)就会触发将$开头的字符串转整数的报错。
  • 附带其他问题:
    1. 未实现__add__方法,两个Money对象相加m1 + m2的逻辑依赖__radd__兜底,不符合加法运算的设计规范
    2. 在__radd__方法中直接修改self的dollars和cents属性,会导致原对象在加法运算后值被篡改,不符合常规加法运算的不可变预期
    3. 函数定义为money_text_2,但最后调用的是money_text(),名称不匹配会触发NameError
    4. 金额格式化使用%2d处理分,当分值小于10时会显示为空格而非前导零,应该用%02d补零

修复后的代码

class Money(object):
    def __init__(self, dollars=0, cents=0):
        self.dollars = dollars + cents//100
        self.cents = cents % 100
    
    # 实现正向加法
    def __add__(self, other):
        total_cents = self.dollars * 100 + self.cents
        if isinstance(other, Money):
            total_cents += other.dollars * 100 + other.cents
        elif isinstance(other, int):
            total_cents += other * 100
        elif isinstance(other, float):
            total_cents += int(other * 100)
        else:
            raise TypeError(f"不支持与{type(other)}类型做加法运算")
        # 返回新的Money对象,不修改原对象
        return Money(cents=total_cents)
    
    # 反向加法直接委托给__add__
    def __radd__(self, other):
        return self.__add__(other)
    
    # 单独实现字符串格式化逻辑,不要把输出和运算耦合
    def __str__(self):
        return f"${self.dollars}.{self.cents:02d}"
    
    # 要实现==判断需要自定义相等逻辑
    def __eq__(self, other):
        if not isinstance(other, Money):
            return False
        return self.dollars == other.dollars and self.cents == other.cents

def money_test():
    m1 = Money(3, 50)
    m2 = Money(2, 60)
    print(m1 == m2) # 输出False
    print(m1 + m2) # 输出$6.10
    print(10 + m1 + m2) # 输出$16.10

money_test()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 14:06:10