You need to enable JavaScript to run this app. Python中已封装BankAccount类实现余额非负约束的方法咨询
优惠活动
大模型
产品
解决方案
定价
更多

Python中已封装BankAccount类实现余额非负约束的方法咨询

BankAccount 类约束实现相关提问

初始测试类代码

class BankAccount:
     def __init__(self, name, balance):
         self.name = name
         self.balance = balance
         self.transaction_fee = 5.00
     def deposit(self, amount):
        self.balance = self.balance + amount
     def withdraw(self, amount):
        self.balance = self.balance - amount

单下划线封装后的类实现

通过给内部属性加单下划线前缀的方式做基础封装后,类代码如下:

class BankAccount:
     def __init__(self, name, balance):
         self._name = name
         self._balance = balance
         self._transaction_fee = 5.00
     def deposit(self, amount):
        self._balance = self._balance + amount
     def withdraw(self, amount):
        self.balance = self.balance - amount

需要落地的业务约束

现在需要对BankAccount类做改造,强制保证以下不变式成立:

  • 账户余额永远不能为负
  • 禁止传入负数的存款金额
  • 禁止取款金额超过账户当前余额

原有实现思路与现存疑问

你最初打算在deposit、withdraw方法里用if/else分支做合法性校验,在deposit方法里的初步实现片段如下:

def deposit(self, amount):
    if amount >= 0:
          self._balance = self._balance + amount
    else ?????

目前存在两个待解决的问题:

  1. 上述代码里的else分支应该如何编写,才能让调用方明确感知到入参不合法、需要重新传入合法值
  2. 除了在业务方法内部硬写if/else判断的方式,有没有其他更合理的方法可以完成上述约束

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 22:54:01