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

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.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:50:26