>A Byte of Python

Class and Object Variables

We will now discuss the data part of the object - the variables. We have two types - the class variables and the object variables. The difference is in the ownership - does the class own the variables or does the object own the variables?

When the class owns the variables, it is called a class variable. Class variables are shared in the sense that they can be accessed by all objects (instances) of that class. When the object owns the variables, it is called an object variable. In this case, each object has its own copy of this variable i.e. they are not shared and are not related in any way to the variable of the same name in a different instance of the same class. An example will make this clearer.

This example, although a long one, helps demonstrate the nature of class and object variables. Here, we refer to the population variable of the Person class as Person.population and not as self.Population. Note that an object variable with the same name as a class variable will hide the class variable!

We refer to the object variable name using self.name in the methods. Remember this simple difference between class and object variables. To summarize, ClassName.field1 refers to the class variable called field1 of the class ClassName. This variable is shared by all instances/objects of this class. The variable self.field2 refers to the object variable of the class and is different in different objects.

Observe that the __init__ method is run first even before we get to use the object and this method is used to initialize the object variables for later use. This is confirmed by the output of the program which indicates when the particular object is initialized.

Notice that when we change the value of Person.population, all the objects use the new value which confirms that the class variables are indeed shared by all the instances of that class. We can also observe that the values of the self.name variable is specific to each object which indicates the nature of object variables. Remember, that you must refer to the variables and methods of the same object using the self variable only. This is called an attribute reference.

In this program, we can also see the use of docstrings for classes as well as methods. We can access the class docstring at runtime such as Person.__doc__ and the method docstring as Person.sayHi.__doc__.

Just like the __init__ method, we can also have a __del__ method where we can decrement the Person.population by 1. This method is run when the object is no longer in use. If you want to try this out, add the __del__ method and then use the statement del personInstance to delete the object. You can use a print statement within this method to see when it is run.