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()
I get this error when I run this code.. AttributeError: Account instance has no attribute 'deposit'
4 Answers 4
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
The way you defined them, they were local to the __init__ method, and thus useless.
Comments
So what the above answers mean is that instead your code should be like this - remember unlike other languages, indentation is serious business in 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()
and now you'll get 1600.23 instead of an error.
Comments
You've indented them too deep. They're inner functions of the __init__() method.
Comments
In addition to what others have remarked:
You have not correctly shown the code that you actually ran. What appears here has the def __init__ ... at the same level as the class statement; this would have caused a (compile time) SyntaxError, not a (run time) AttributeError.