我需要储蓄帐户不被更改为小于500的值。构造函数balance不应接受任何低于500的值。代码运行良好,一切正常。存取款方法可以正常工作,但我不知道如何防止余额小于500的变量访问储蓄帐户。
class BankAccount(object):
def __init__(self):
pass
def withdraw(self):
pass
def deposit(self):
pass
class SavingsAccount(BankAccount):
def __init__(self, balance=500):
self.balance = balance
def deposit(self, deposit):
if self.deposit > 0:
self.balance += deposit
return self.balance
else:
return "Invalid deposit amount"
def withdraw(self, withdraw):
if self.balance < withdraw:
return "Cannot withdraw beyond the current account balance"
elif (self.balance - withdraw) < 500:
return "Cannot withdraw beyond the minimum account balance"
elif withdraw < 0:
return "Invalid withdraw amount"
else:
self.balance -= withdraw
return self.balance
class CurrentAccount(BankAccount):
def __init__(self, balance=0):
self.balance = balance
def deposit(self, deposit):
if self.deposit > 0:
self.balance += deposit
return self.balance
else:
return "Invalid deposit amount"
def withdraw(self, withdraw):
if withdraw < 0:
return "Invalid withdraw amount"
elif self.balance < withdraw:
return "Cannot withdraw beyond the current account balance"
else:
self.balance -= withdraw
return self.balance发布于 2017-02-22 14:04:52
class SavingsAccount(BankAccount):
def __init__(self, balance=500):
if balance < 500:
raise ValueError("SavingsAccount balance must be at least 500")
self.balance = balance您还可以定义自定义异常:
class BalanceTooLowError(ValueError):
"""Raise if attempting to set an account balance to a disallowed value"""https://stackoverflow.com/questions/42383637
复制相似问题