问题描述
我有这个测试程序:
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,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 部分,我不知道如何让它回到函数并再次请求一个正确的值。
还有其他方法可以做到这一点吗?
谢谢
解决方法
处理这个问题的一种方法是为此模块定义一个异常类(例如AccountError
),并在有人试图存入负数(或做任何其他不允许的事情)时引发该异常。
在调用 deposit()
方法的地方,您可以捕获异常(借助 try
-except
-块)并允许用户重试输入了无效值。
它可能看起来像这样:
class AccountError(Exception):
"""Module specific error"""
class BankAccount:
...
...
...
def deposit(self,amount):
if amount >= 0:
self._balance = self._balance + amount
else:
raise AccountError("Deposit amount cannot be negative")
(当然,您可以向异常添加更多信息和功能。)
在代码被调用的地方:
account = BankAccount()
...
...
try:
account.deposit(negative_amount)
except AccountError as exc:
# Code that allows you to retry the deposit.
# Implementation depends on your program structure.
整个块可以嵌入到 for
或 while
循环中,并进行一定数量的重试,或者在您的情况下有意义的任何内容。
具体的实现将取决于您的程序的结构和作用。
,在您的方法中,您可以返回一个指示成功或失败的布尔值。然后调用代码可以适当处理。
如果您担心调用代码可能会忽略返回值并且事务会默默地失败,您可以改为引发异常并让调用代码来处理 - 类似这样:
class BankAccount:
def __init__(self,name,balance):
self._name = name
self._balance = balance
self._transaction_fee = 5.00
def deposit(self,amount):
if (self._balance + amount) < 0:
raise Exception("Balance cannot go below 0.")
else:
self._balance = self._balance + amount
def withdraw(self,amount):
if (self._balance - amount) < 0:
raise Exception("Balance cannot go below 0.")
else:
self._balance = self._balance - amount
在现实生活中,您会创建自己的 Exception 子类并引发它。