2016-09-17 58 views
-2
class Account(object): 
    def __init__(self,holder, number, balance, credit_line = 1500): 
     self.holder = holder 
     self.number = number 
     self.balance = balance 
     self.credit_line = credit_line 

    def deposit(self, amount): 
     self.balance = amount 
    def withdraw(self, amount): 
     if(self.balance - amount < -self.credit_line): 
      return False 
     else: 
      self.balance -= amount 
      return True 

    def balance(self): 
     return self.balance 
    def holder(self): 
     return self.holder 

    def transfer(self, target, amount): 
     if(self.balance - amount < -self.credit_line): 
      #coverage insufficient 
      return False 
     else: 
      self.balance -= amount 
      target.balance += amount 
      return True 
Guido = Account("Guido", 10 ,1000.50) 
Guido.balance() 
------------------------------------------------------------------------- 


Traceback (most recent call last): 
    File "Account.py", line 31, in <module> 
    Guido.balance() 
TypeError: 'float' object is not callable 
+0

'self.balance = amount'覆蓋'balance'函數 –

+0

其他答案已經解釋了這個問題,但我只是想說,像「balance」和「holder」方法的「訪問器」通常在Python中不需要。你可以讓你的外部代碼直接訪問該屬性(在這種情況下,它是相同的名稱,導致問題)。如果您後來發現需要對值進行一些特殊處理(例如將其舍入到一定的小數位數),則可以使用「property」將屬性查找轉換爲函數調用。 – Blckknght

回答

1

在您的__init__方法中,您正在覆蓋方法balance。您可以將字段名稱更改爲_balance或僅刪除balance方法並使用Guido.balance

還要注意,您應該爲您的變量很快與小寫字母(即guido = Account(...),不Guido

0
class Account(object): 
    def __init__(self,holder, number, balance, credit_line = 1500): 
     self.holder = holder 
     self.number = number 
     self.balance = balance 
     self.credit_line = credit_line 

    def deposit(self, amount): 
     self.balance = amount 
    def withdraw(self, amount): 
     if amount > self.balance: 
      print "Amount greater than available balance" 

     else: 
      self.balance -= amount 
      return True 

    def bala_nce(self): 
     return self.balance 
    def hold_er(self): 
     return self.holder 
    def num(self): 

     return self.number 


    def transfer(self, target, amount): 
     if(self.balance - amount < -self.credit_line): 
      #coverage insufficient 
      return False 
     else: 
      self.balance -= amount 
      target.balance += amount 
      return True 

guido = Account("Guido", 10 ,10000.100) 
guido.withdraw(2300.100) 

print "Account name: " ,guido.hold_er() 
print "available balance: $",guido.bala_nce() 

感謝名單開始你...............它的工作現在