如何在Python的BankAccount类中实现跨账户转账的transaction交易方法
解决方案
现有代码问题梳理
- 原有
transfer方法仅操作当前账户本身,未传入收款账户对象,导致扣款后只能给自己加钱,无法实现跨账户转账 - 主函数中实例变量名定义与调用不一致:定义时为
account1、account2,调用时错写为a1、a2,会触发变量未定义报错 - 原有存取款方法无合法性校验,可能出现负余额、转账负数等逻辑错误
功能实现思路
transfer方法需要新增两个入参:收款方的BankAccount实例对象、转账金额,执行逻辑如下:
- 调用当前账户的
withdraw方法扣除对应金额,校验余额充足、金额合法 - 调用收款方账户的
deposit方法增加对应金额
完整可运行代码
class BankAccount: def __init__(self, first_name, last_name, number, balance): self._first_name = first_name self._last_name = last_name self._number = number self._balance = balance def deposit(self, amount): if amount <= 0: raise ValueError("存款金额必须为正数") self._balance += amount def withdraw(self, amount): if amount <= 0: raise ValueError("取款金额必须为正数") if amount > self._balance: raise ValueError("账户余额不足,无法完成操作") self._balance -= amount def get_balance(self): return self._balance # 修正后的转账方法 def transfer(self, target_account, amount): self.withdraw(amount) target_account.deposit(amount) def print_info(self): s = f"{self._first_name} {self._last_name}, {self._number}, balance: {self._balance}" print(s) def main(): account1 = BankAccount("Jesse", "Pinkman", "19371554951", 20_000) account2 = BankAccount("Walter", "White", "19371564853",500) # 从account1向account2转账200元 account1.transfer(account2, 200) account1.print_info() account2.print_info() main()
运行输出结果
Jesse Pinkman, 19371554951, balance: 19800 Walter White, 19371564853, balance: 700
内容的提问来源于stack exchange,提问作者fredericoamigo
相关产品推荐
相关产品推荐

