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

银行账户项目问题:无法调用get方法返回余额,解释器忽略调用

问题分析与解决方案

核心问题点

  1. 方法调用未加括号
    最后一行代码c.getDepositHistory只是引用了方法对象,并没有执行方法。必须添加括号()才能触发方法执行,正确写法是c.getDepositHistory(),getBalance同理。

  2. 交易记录未保存为实例属性
    deposit方法里的depositHistory是局部变量,仅在该方法内部有效,getDepositHistory无法访问到它。同理withdraw里的withdrawHistory也是局部变量,无法被外部方法获取。

修正后的完整代码

class Category:
    def __init__(self, balance=0):
        self.balance = balance
        # 初始化存款、取款历史列表
        self.deposit_history = []
        self.withdraw_history = []

    def deposit(self, value1, description1=""):
        deposit_record = {"amount": value1, "description": description1}
        self.deposit_history.append(deposit_record)
        self.balance += value1
        print(f"存款金额: {value1},当前余额: {self.balance}")

    def withdraw(self, value2, description2=""):
        if self.balance >= value2:
            withdraw_record = {"amount": value2, "description": description2}
            self.withdraw_history.append(withdraw_record)
            self.balance -= value2
            print(f"取款金额: {value2},当前余额: {self.balance}")
        else:
            print("余额不足!")

    def getDepositHistory(self):
        return self.deposit_history

    def getBalance(self):
        return self.balance

    def getWithdrawHistory(self):
        return self.withdraw_history

    def transfer(self, value3):
        if self.balance > value3:
            self.balance -= value3
            print(f"转账金额: {value3},当前余额: {self.balance}")
        else:
            print("资金不足!")


# 测试执行
c = Category(100)
c.deposit(300, "hello")
c.withdraw(200)
c.transfer(50)
# 正确调用方法并打印结果
print("存款历史:", c.getDepositHistory())
print("当前余额:", c.getBalance())

修正说明

  • 在__init__中初始化了deposit_history和withdraw_history列表,专门存储交易记录。
  • deposit和withdraw方法中,将每次的交易记录添加到对应的实例列表,而非局部变量。
  • 调用方法时添加括号,确保方法执行,同时打印返回值,就能看到预期的余额和交易历史数据。
  • 优化了打印语句格式,用f-string让输出更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:57:14