I (accidentally) wrote the following code:
#!/usr/bin/python3.4
class Account:
balance = 1000
def withdraw(self, amount):
print('Withdrawing')
if(amount > self.balance):
print("You cannot withdraw that amount!")
else:
self.balance -= amount
def checkBalance(self):
if (self.balance == 0):
print("Your account is empty.")
else:
print("You still have ", str(self.balance) + "€ euros in your account!")
def Main():
account1 = Account()
account2 = Account()
account1.withdraw(100)
account1.withdraw(300)
account1.checkBalance()
account2.checkBalance()
if __name__ == "__main__":
Main()
output:
Withdrawing
Withdrawing
You still have 600€ euros in your account!
You still have 1000€ euros in your account!
My questions:
1) why the balance
variable does not behave as a class (static) variable although it has been declared as such?
2) even if the usage of the self
keyword when accessing the balance
variable from within the methods is preventing the static behavior, at which point is an instance copy of the class variable balance
made? (at least that is what I am inferring, that each object gets its own copy of the -what is supposed to be a class variable- balance
)
3) by trial and error, I discovered that a way to get the (expected?) behavior is to annotate the methods with @classmethod. Is this s.th like in Java that prevents access of static variables from non-static methods?
I am aware of this and this posts but IMHO they do not address the above implications.