我需要儲蓄帳戶不能更改爲小於500的值。構造器餘額不應接受任何低於500的值。代碼運行良好且沒問題。存款和取款方法正常工作,但我不知道如何防止其餘額低於500的變量訪問儲蓄賬戶。Python面向對象的固定帳戶
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
所以,你希望它是不可能創建一個新的'SavingsAccount(餘額= 499)'?爲什麼不添加「如果餘額<500:將BalanceTooLowError()'提升到'SavingsAccount' __init__'? – KernelPanic
@KernelPanic這正是我想要的.....就讓我試試吧,我會盡快給您 – Nix
爽:)張貼作爲一個答案 – KernelPanic