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

如何解决Python使用class类编写银行账户功能时出现的TypeError错误

报错原因与修复方案

核心报错原因

  • 初始化用户时,amount属性被赋值为字符串类型:input()函数默认返回字符串,代码中直接将input('Enter the balance: ')的结果赋值给test[user_id].amount,没有做整数转换,和你定义的amount: int类型标注也不匹配。
  • deposit方法逻辑错误:self.amount += int(self.amount) + x等价于self.amount = self.amount + int(self.amount) + x,当self.amount为字符串时,+会执行字符串拼接逻辑,和后续的整数值相加就会触发类型错误。即使amount是整数类型,该逻辑也不符合存款规则,会重复叠加一次原有本金。

修复步骤

  1. 修正用户初始化时的余额赋值逻辑,将输入转为整数:
    将test[user_id].amount = input('Enter the balance: ')修改为:
test[user_id].amount = int(input('Enter the balance: '))
  1. 修正存款方法的逻辑,仅叠加存款金额:
    将原deposit方法修改为:
def deposit(self, x):
    self.amount += x
  1. 修复隐藏bug:添加用户分支中test.append(BankAccount)是将类本身追加到列表,应追加类的实例,修改为:
test.append(BankAccount())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:18:03