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

Python实现银行Accounts对象时bin()调用报TypeError排查

银行账户功能报错修复方案

开发需求

  • 创建适用于银行系统的Accounts对象
  • 账户初始化接收三个入参:Firstname(名)、Lastname(姓)、初始存款金额
  • 实现4个成员方法:Deposit(存款)、Withdraw(取款)、Fee Calculations(手续费计算)、interest(利息计算),业务规则为:账户余额低于1000美元时每月收取10美元手续费,利息率为3%。

报错根因定位

触发栈中TypeError: 'str' object cannot be interpreted as an integer的直接原因:

bin()函数仅支持整数类型入参,原代码在执行d = bin(d)前,已经通过d = '{:.2f}'.format(d)将浮点型金额转换为了字符串类型,字符串无法被bin()解析,直接抛出类型错误。整数金额场景下代码未出现该报错,是因为当时未做格式化转字符串的操作。

除表层报错外,原代码存在多处逻辑缺陷,即使修复类型问题也无法满足需求:

  • 冗余的二进制转换逻辑:金额计算完全不需要转二进制操作,这部分属于无效逻辑,也是类型错误的核心诱因
  • 变量作用域混乱:所有方法直接读写全局变量,Withdraw方法中格式化金额时误引用全局变量d,完全没有使用入参w
  • 余额计算逻辑失效:没有维护实时更新的账户余额,存、取款计算始终基于初始存款值,sum()函数调用方式也不符合语法要求
  • 业务实现偏离需求:未按要求封装Accounts类,手续费、利息计算未关联实时账户余额,利息计算时强转金额为int会丢失小数精度

修复后完整实现

class Accounts:
    def __init__(self, first_name, last_name, init_deposit):
        self.first_name = first_name
        self.last_name = last_name
        # 金额统一保留两位小数精度存储
        self.balance = round(float(init_deposit), 2)

    def Deposit(self, amount):
        """存款方法,存入指定金额后返回最新余额"""
        amount = round(float(amount), 2)
        if amount <= 0:
            raise ValueError("存款金额必须大于0")
        self.balance = round(self.balance + amount, 2)
        return self.balance

    def Withdraw(self, amount):
        """取款方法,取出指定金额后返回最新余额"""
        amount = round(float(amount), 2)
        if amount <= 0:
            raise ValueError("取款金额必须大于0")
        if amount > self.balance:
            raise ValueError("账户余额不足,无法完成取款")
        self.balance = round(self.balance - amount, 2)
        return self.balance

    def FeeCalc(self):
        """月度手续费计算,余额低于1000美元收取10美元手续费,扣收后返回手续费金额"""
        fee = 10.0 if self.balance < 1000 else 0.0
        self.balance = round(self.balance - fee, 2)
        return round(fee, 2)

    def Interest(self):
        """按3%年利率计算利息,计息入帐后返回利息金额"""
        interest = round(self.balance * 0.03, 2)
        self.balance = round(self.balance + interest, 2)
        return interest


if __name__ == "__main__":
    input_content = 'John Doe 4893.27'
    account_params = input_content.split()
    # 初始化账户实例
    acc = Accounts(account_params[0], account_params[1], account_params[2])
    initial_balance = acc.balance
    # 执行276.84美元取款操作
    acc.Withdraw(276.84)
    # 计算当月手续费
    month_fee = acc.FeeCalc()
    # 计算年利息
    year_interest = acc.Interest()

    # 输出账户信息
    print(f"{acc.first_name} {acc.last_name} account information:")
    print(f"Initial deposit: ${initial_balance:.2f}")
    print(f"New balance: ${acc.balance:.2f}")
    print(f"Fee: ${month_fee:.2f}")
    print(f"Interest: ${year_interest:.2f}")

实现说明

  • 严格按照需求封装Accounts类,初始化入参、成员方法完全匹配要求
  • 存、取款方法增加金额合法性校验,操作后自动更新账户余额
  • 手续费、利息计算均基于实时账户余额,规则完全符合需求定义
  • 所有金额运算全程保留两位小数精度,支持小数金额场景,不会出现类型转换错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 09:45:38