【发布时间】:2021-03-02 09:27:38
【问题描述】:
我有这个测试程序:
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 类以强制执行帐户余额永远不会变为负数的不变量。这意味着您应该禁止负存款,禁止超过账户余额的提款。
我曾想过在存款和取款功能中使用 if/else 语句。例如:
def deposit(self, amount):
if amount >= 0:
self._balance = self._balance + amount
else ?????
else部分,我不知道如何让它回到函数并再次要求一个合适的值。
还有其他方法可以做到这一点吗?
谢谢
【问题讨论】:
-
如果您在
deposit()方法中强制执行非负金额,那么您不需要else:。如果您在deposit()之外强制执行此操作,那么您可以对此采取一些措施。
标签: python python-3.x oop encapsulation