2010-06-12 26 views
0
class Account: 
    def __init__(self, initial): 
     self.balance = initial 
     def deposit(self, amt): 
      self.balance = self.balance + amt 
     def withdraw(self,amt): 
      self.balance = self.balance - amt 
     def getbalance(self): 
      return self.balance 

a = Account(1000.00) 
a.deposit(550.23) 
a.deposit(100) 
a.withdraw(50) 

print a.getbalance() 

我得到這個錯誤,當我運行此代碼.. AttributeError的:帳戶實例沒有屬性「存款」AttributeError幫助!

+0

您的縮進是錯誤的。 – 2010-06-12 02:20:05

回答

2

那麼上述答案的意思是,不是你的代碼應該是這樣的 - 還記得與其它語言不同,壓痕嚴重的企業在Python:

class Account(object): 

    def __init__(self, initial): 
     self.balance = initial 

    def deposit(self, amt): 
     self.balance += amt 

    def withdraw(self, amt): 
     self.balance -= amt 

    def getbalance(self): 
     return self.balance 

a = Account(1000.00) 
a.deposit(550.23) 
a.deposit(100) 
a.withdraw(50) 

print a.getbalance() 

,現在你會得到1600.23,而不是一個錯誤的。

5
class Account: 
    def __init__(self, initial): 
     self.balance = initial 
    def deposit(self, amt): 
     self.balance = self.balance + amt 
    def withdraw(self,amt): 
     self.balance = self.balance - amt 
    def getbalance(self): 
     return self.balance 

你定義它們的方式,他們是本地的__init__方法,因此沒用。

2

你已經縮短了它們太深。它們是__init__()方法的內部功能。

0

除了別人怎麼說:

您還沒有正確顯示,你居然跑的代碼。此處顯示的def __init__ ...class聲明處於同一級別;這會導致(編譯時)SyntaxError,而不是(運行時)AttributeError。