Python面向对象账户存款与扣款功能代码实现咨询
账户扣款功能实现方案
扣款功能需要覆盖几个核心逻辑,以下是具体实现和完善后的完整代码:
class Account: last_id = 1000 def __init__(self, customer): self.customer = customer Account.last_id += 1 self.id = Account.last_id self._balance = 0 def deposit(self, amount): if amount > 0: self._balance += amount print(f'Deposit successful, current balance: {self._balance}') else: print('Invalid deposit amount, must be greater than 0') def charge(self, amount): # 验证扣款金额合法性 if amount <= 0: print('Invalid charge amount, must be greater than 0') return # 检查余额是否充足 if self._balance >= amount: self._balance -= amount print(f'Charge successful, current balance: {self._balance}') else: print('Insufficient balance for this charge')
逻辑说明:
- 先判断扣款金额是否为正数,若不是直接提示无效金额
- 余额足够时,从账户余额中扣除对应金额并打印更新后的余额
- 余额不足时,提示无法完成扣款操作
另外修正了原deposit方法的不合理提示:原代码中金额不大于0时错误提示“操作成功”,现在改为提示无效金额,逻辑更严谨。
内容的提问来源于stack exchange,提问作者Mery p.
相关产品推荐
相关产品推荐

