06.10.2011
Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods.
Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class.
On use via instance (self.x), search order:
(this also works for method lookup)
On assignment via instance (self.x = …) ALWAYS makes an instance variable
Class Variable
class A(object): class_var = 0 # defined here def __init__(self): A.class_var += 1 # self.class_var +=1 -> transform it to instance variable if __name__ == "__main__": first_ob = A() print first_ob.class_var second_ob = A() print second_ob.class_var third_ob = A() print third_ob.class_var
The run of this script will give:
$ python test.py 1 2 3
Note: if instead of class_var = 0, you'd have class_var = [] (a list), and you'd be using self.class_var.append(elem), the list will be shared among class objects and it will always add new elements.
self here will get the class variable (because there is no instance variable) and append to it, thus the kind of the variable will no be changed.
Note: using self.class_var += 1 is equivalent to self.class_var = self.class_var + 1 which is in fact an assignment via instance (transforming it into instance variable from class variable)