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
bar.num += 1
creates a new instance variable 'num' on the 'bar' instance because it doesn't yet exist (and then adds 1 to this value)
an example:
class Foo:
def __init__(self):
self.num= 1
bar = Foo()
print bar.num
this prints 1
print bar.foo
this gives an error as expected: Traceback (most recent call last): File "", line 1, in AttributeError: Foo instance has no attribute 'foo'
bar.foo = 5
print bar.foo
now this prints 5
so what happens in your example: bar.num is resolved as Foo.num because there's only an class attribute. then foo.num is actually created because you assign a value to it.