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

Python银行程序中Bank与Account类关联及转账报错排查

问题分析与修复方案

1. Bank类初始化赋值错误

原__init__方法中错误地将address赋值给self.name,导致银行名称被地址覆盖,修正如下:

def __init__(self, name, address):
    self.name = name
    self.address = address  # 修正赋值目标

2. 账户存储键值逻辑错误

create_account方法使用Account类作为字典键,每次创建新账户都会覆盖之前的条目(因为键始终是同一个类对象)。需要改用唯一标识(如用户全名组合)作为键,同时返回该标识以便后续操作:

def create_account(self, firstname, lastname, balance):
    account = Account(firstname, lastname, balance)
    # 用小写全名拼接作为唯一键(若需支持重名,可生成唯一账号ID)
    account_key = f"{firstname.lower()}_{lastname.lower()}"
    self.all_accounts[account_key] = account
    return account_key  # 返回键,用于后续转账、查询操作

3. create_account无返回值导致后续操作失效

原方法没有返回值,因此ac1 = bank.create_account(...)会得到None,无法用于后续转账调用。上述修改已添加return account_key,调用时可获取有效标识:

# 测试代码修正
bank = Bank("Bank of Westeros", "1 Park Place, Westeros, GoT")
ac1_key = bank.create_account("Carrot", "Top", 5000)
ac2_key = bank.create_account("Dolly", "Parton", 10000)

4. 转账方法的参数匹配与校验缺失

原transfer方法未校验账户是否存在,直接通过键取值会引发KeyError。修正后添加账户存在性校验,确保操作安全:

def transfer(self, ac1_key, ac2_key, amount):
    if ac1_key not in self.all_accounts or ac2_key not in self.all_accounts:
        print("账户不存在")
        return False
    if self.all_accounts[ac1_key].withdraw(amount):
        self.all_accounts[ac2_key].deposit(amount)
        print("转账成功")
        return True
    return False

5. Account类transfer方法冗余

原Account类的transfer方法仅实现了金额输入和成功提示,无实际转账逻辑。转账操作应由Bank类统一管控(确保账户存在、余额充足等),因此可删除该方法。


修复后完整代码示例

Bank类(bank.py)
from account import Account


class Bank:
    def __init__(self, name, address):
        self.name = name
        self.address = address
        self.all_accounts = {}  # 改为实例属性,避免多个Bank实例共享账户列表

    def create_account(self, firstname, lastname, balance):
        account = Account(firstname, lastname, balance)
        account_key = f"{firstname.lower()}_{lastname.lower()}"
        self.all_accounts[account_key] = account
        return account_key

    def show_accounts(self, show_history=False):
        for key, account in self.all_accounts.items():
            print(f"\n账户标识: {key}")
            account.desc()
            if show_history:
                print("交易历史:", account.history)

    def transfer(self, ac1_key, ac2_key, amount):
        if ac1_key not in self.all_accounts or ac2_key not in self.all_accounts:
            print("账户不存在")
            return False
        if self.all_accounts[ac1_key].withdraw(amount):
            self.all_accounts[ac2_key].deposit(amount)
            print("转账成功")
            return True
        return False

    def get_account(self, account_key):
        return self.all_accounts.get(account_key, None)
Account类(account.py)
class Account:
    def __init__(self, firstname, lastname, balance=0):
        self.firstname = firstname
        self.lastname = lastname
        self.balance = balance
        self.number_of_deposits = 0
        self.number_of_withdraws = 0
        self.history = []

    def desc(self):
        print(f"姓名: {self.firstname} {self.lastname}")
        print(f"余额: ${self.balance}")
        return True

    def deposit(self, value):
        if value <= 0:
            print("存款金额必须大于0")
            return False
        self.balance += value
        self.history.append(f"存款 +${value}")
        self.number_of_deposits += 1
        return True

    def withdraw(self, value):
        if value <= 0:
            print("取款金额必须大于0")
            return False
        if self.balance < value:
            print(f"{self.firstname} {self.lastname} 余额不足")
            return False
        self.balance -= value
        self.history.append(f"取款 -${value}")
        self.number_of_withdraws += 1
        return True
测试代码
from account import Account
from bank import Bank

bank = Bank("Bank of Westeros", "1 Park Place, Westeros, GoT")

ac1_key = bank.create_account("Carrot", "Top", 5000)
ac2_key = bank.create_account("Dolly", "Parton", 10000)

# 执行转账
bank.transfer(ac1_key, ac2_key, 2000)

# 查看所有账户及交易历史
bank.show_accounts(show_history=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:25:20