To understand the difference, you need to consider the difference between classes and instances of these classes.
Class attributes apply to every object of this class. Modifying them changes all instances of this class. Changing the attributes of an instance only changes the specific object being processed.
For instance:
class Foo: class_var = 'bar' def __init__(self): self.instance_var = 'baz' foo1 = Foo() foo2 = Foo() print(foo1.class_var, foo2.class_var) print(foo1.instance_var, foo2.instance_var) Foo.class_var = 'quux' Foo.instance_var = "this doesn't work" foo1.instance_var = 'this does' print(foo1.class_var, foo2.class_var) print(foo1.instance_var, foo2.instance_var)
prints
bar bar baz baz quux quux this does baz
So, changing Foo.class_var replaces class_var for all existing instances of Foo , and modifying Foo.instance_var does nothing. However, changing the instance_var object of type Foo works, but only for this particular instance — other instances are not changed.
source share