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

如何修改Python类实例?类实例金额相加未生效问题排查

问题原因与解决方案

问题根源

你的代码中__add__方法的逻辑存在错误:

  • 虽然你在方法里修改了当前实例的money值,但最终返回的是全新创建的Bank实例——这个新实例会使用__init__中的默认值money=50,所以执行h1 = h1 + h2后,h1指向的是这个默认金额的新实例,自然输出Br1 50。
  • 另外,你的写法不符合Python中+运算符的常规语义:+通常应该返回新对象,而非修改原对象。

解决方案

方案1:返回修改后的原实例(快速实现需求)

修改__add__方法,直接返回修改后的自身,这样h1仍然指向原实例,金额已更新:

class Bank:
    def __init__(self, name):
        self.name = name
        self.money = 50

    def __add__(self, other):
        if isinstance(other, Bank):
            self.money += other.money
            return self

    def info(self):
        print(self.money)


h1 = Bank('Br1')
h2 = Bank('Br2')
h1 = h1 + h2

print(h1.name, h1.money)  # 输出 Br1 100

方案2:返回携带计算后金额的新实例(推荐,符合Python规范)

先修改__init__方法支持自定义初始金额,再让__add__返回新的实例:

class Bank:
    # 新增可选的money参数,默认值保持50
    def __init__(self, name, money=50):
        self.name = name
        self.money = money

    def __add__(self, other):
        if isinstance(other, Bank):
            # 创建并返回新实例,金额为两者之和
            return Bank(self.name, self.money + other.money)

    def info(self):
        print(self.money)


h1 = Bank('Br1')
h2 = Bank('Br2')
h1 = h1 + h2

print(h1.name, h1.money)  # 输出 Br1 100

这种方式不会修改原有的h1、h2实例,完全符合Python中+运算符的设计逻辑(比如a = b + c不会改变b的值)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:35:20