User Tools

Site Tools


python:class_instance_variables

Difference between CLASS and INSTANCE variables

updated 26.01.2016

06.10.2011

Theory

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 methods.
Instance (or Object) variable: A variable that is defined inside a method and belongs only to the current instance of a class.

Notes

On use via instance (self.x), search order:

  1. instance
  2. class
  3. base classes

(this also works for method lookup)

On assignment via instance (self.x = …) ALWAYS makes an instance variable.

Examples

Now a couple of examples to understand different behaviours:

Shared class variable

class Visitor:
    counter = 0
 
    def __init__(self):
        type(self).counter += 1
        # similar Visitor.counter but it doesn't help with inheritance
 
v1 = Visitor()
v2 = Visitor()
v3 = Visitor()
 
print("Final shared counter {} or {}".format(Visitor.counter, v2.counter))
# Displays: Final shared counter 3 or 3

Using self, you can transform a class variable into an instance variable.
The class variable will exist separately of the instance one.

Transformed class variable

class Visitor:
    counter = 0
 
    def __init__(self):
        self.counter += 1
        # this is making the above counter variable - instance type 
 
v1 = Visitor()
v2 = Visitor()
v3 = Visitor()
 
print("Final shared counter {} or {}".format(Visitor.counter, v3.counter))
# Final shared counter 0 or 1
 
print(Visitor.__dict__)
print(v1.__dict__)

Mixing those two type will result in a strange behaviour for the programmer:

Messing with variables type

class Visitor:
    counter = 0
 
    def __init__(self):
        self.counter += 1
 
 
v1 = Visitor()
Visitor.counter = 100 
print("Counter v1: {}".format(v1.counter)) # displays 1, v1 init already take place
 
v2 = Visitor()
Visitor.counter = 200
print("Counter v2: {}".format(v2.counter)) # displays 101 (previous 100 + 1)
 
v3 = Visitor()
print("Counter v1: {}".format(v3.counter)) # displays 201 (previous 200 + 1)

Example with a different type of a shared variable:

Using a list as shared variable

class Visitor:
    items = []
 
    def __init__(self):
        print("Previous items: {}".format(self.items))
 
    def add_item(self, item_name):
        self.items.append(item_name)
 
 
 
v1 = Visitor()  # displays Previous items: []
v1.add_item("suit")
 
v2 = Visitor()  # displays Previous items: ['suit']
v2.add_item("t-shir t")
 
v3 = Visitor()  # displays Previous items: ['suit', 't-shirt']
v3.add_item("pullover")

python/class_instance_variables.txt · Last modified: 2016/01/26 10:23 (external edit)