I’ve been trying to understand Python’s handling of class and instance variables. In particular, I found this answer quite helpful. Basically it says that if you declare a class variable, and then you do an assignment to [instance].property, you will be assigning to a different variable altogether — one in a different namespace from the class variable.
So then I considered — if I want every instance of my class to have a member with some default value (say zero), should I do it like this:
class Foo:
num = 0
or like this?
class Foo:
def __init__(self):
self.num = 0
Based on what I’d read earlier, I’d think that the second example would be initializing the ‘right’ variable (the instance instead of the class variable). However, I find that the first method works perfectly well too:
class Foo:
num = 0
bar = Foo()
bar.num += 1 # good, no error here, meaning that bar has an attribute 'num'
bar.num
>>> 1
Foo.num
>>> 0 # yet the class variable is not modified! so what 'num' did I add to just now?
So.. why does this work? What am I not getting? FWIW, my prior understanding of OOP has come from C++, so explanation by analogy (or pointing where it breaks down) might be useful.
Personally, I’ve found these documents by Shalabh Chaturvedi extremely useful and informative regarding this subject matter.
bar.num += 1is a shorthand forbar.num = bar.num + 1. This is picking up the class variableFoo.numon the righthand side and assigning it to an instance variablebar.num.