2017-02-22 38 views
0

我需要儲蓄帳戶不能更改爲小於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 
+0

所以,你希望它是不可能創建一個新的'SavingsAccount(餘額= 499)'?爲什麼不添加「如果餘額<500:將BalanceTooLowError()'提升到'SavingsAccount' __init__'? – KernelPanic

+0

@KernelPanic這正是我想要的.....就讓我試試吧,我會盡快給您 – Nix

+0

爽:)張貼作爲一個答案 – KernelPanic

回答

0
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""" 
+0

非常感謝我不是專家yet..the問題,我試圖要返回一條消息,但__init__方法不應該返回任何東西......我將閱讀更多關於raise和errors的內容。 – Nix

+1

我很欣賞。我正在研究它,希望我會得到更多的答案。已經檢查過 – Nix