Search This Blog

Thursday, August 9, 2012

Difference between class and instance variables in Python

Object oriented programming in Python can be tricky if your background comes from C++ or Java. First thing is that both C++ and Java are statically typed. This is different in Python that belongs to the class of dynamic scoped languages [4].

For Java and C++ for example if you forget to declare a variable before you try to access it it will generate an error during compilation phase. Below is an example code in Java that illustrates this.


$ javac cannot find symbol
symbol  : variable number
location: class JavaExample
        ^ cannot find symbol
symbol  : variable number
location: class JavaExample
       System.out.println("[test " + number + "] list=%s");
2 errors

When you start applying object oriented programming paradigms in Python and start to write classes and create instances you may encounter an interesting phenomena. The code below illustrate this.

The difference between the 2 classes is that in the class Test2ClassVariable we have defined this variable self.mylist=[] additionally.

When you run this code this is the output:
$ python
[test 1] list=one
[test 2] list=one two
[test 3] list=three
[test 4] list=four
The interesting part of the output is in line #3. The variable list has 2 entries where at first look we would expect it should have only one. Not knowing anything about objects in Python this would be a natrual intuition for everyone with Java or C++ background.


We see this behavoiur because Python uses a concept of class and instance variables. For Java/C++ programmers a python class variable is simply a Java/C++ static class variable. In our example variable list is a class variable and it is shared between all class instances. That explains the output we see.


No comments:

Post a Comment