foo
refers to the class, self
refers to the object.
Class members are a property of the class (and thus are shared between all objects of that class), while instance members are a property of the specific object, so a change to an instance member affects only the given object.
When you operate on an object, the members it has are a merge of the class members and the instance members. When two members with the same name are defined, the instance members have the priority.
Thus:
bar
sets an instance variable; that change has effect only on the current instance, so if you do:
b=bar(10)
c=bar(20)
you'll see that c.var
is 20
and b.var
is 10
; nothing strange here;
foo
sets a class variable, which is common to all the instances; so, if you do:
f=foo(10)
g=foo(20)
you'll see that both f.var
and g.var
will be 20
, because they both actually refer to foo.var
, that was last set to 20
in g
's constructor;
on the other hand, instance variables shadow class variables; so, if you do
f=foo(10)
g=foo(20)
f.var=30
you'll have g.var==foo.var==20
, but f.var==30
, since now f.var
refers to the instance variable f.var; but, if you do
del f.var
now the instance (f
's) attribute var
no longer exists, and thus f.var
refers again to the class attribute var
(thus f.var==g.var==foo.var==20
).
Long story short: normally you'll want to use self.var
(i.e. instance members); classname.var
is only for sharing stuff between all instances of a given class.