First of all, to explain it easier, you have to know that doing a.variable += 1
is the same that doing a.variable = a.variable + 1
.
Now, that being said, here is "the problem".
The thing here, is that when you access a.variable
, the interpreter doesn't find the attribute in the instance, so it look that attribute on the class. When it find it, it will return that value. So, a.variable = a.variable + 1
becomes a.variable = 0 + 1
. Now, the interpreter will go to the instance, and look for the attribute variable
. It doesn't find it, so it create it and set it as one.
But what? Then you never changed the attribute variable
from the class Game
? The answer is no. To check this, try this code.
class Game:
variable = 0
def function(self):
print("This is a message inside the class.")
a = Game()
print('Instance attributes before set:', a.__dict__)
print('Class attributes before set', Game.__dict__)
a.variable += 1
print('Instance attributes before set:', a.__dict__)
print('Class attributes after set:', Game.__dict__)
As you can see, you never changed the class atribute. If you want to change the class attribute, you have to do
Game.variable += 1
Hope it helps