Reputation: 2889
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'
Upvotes: 0
Views: 310
Reputation: 82934
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.
Upvotes: 0
Reputation: 4019
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.
Upvotes: 2
Reputation: 798676
You've indented them too deep. They're inner functions of the __init__()
method.
Upvotes: 2
Reputation: 284816
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.
Upvotes: 5