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.

Java

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

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 object_variables_example.py
[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.

Explanation

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.

References
  1. http://stackoverflow.com/questions/68645/static-class-variables-in-python
  2. http://docs.python.org/tutorial/classes.html#instance-objects
  3. http://en.wikipedia.org/wiki/Class_variable
  4. http://en.wikipedia.org/wiki/Python_(programming_language)

No comments:

Post a Comment