Jun 6, 2012

Python super() method and class inheritance

There is one more useful method in python. super()

It helps to handle inheritance of ancestor class. This sounds a bit of messy. So I'll try to explain.

You have class A that does some useful things. And you have to use this class A everywhere in your application with adding some piece of functionality. You may inherit this class B(A) and expand it's functionality. Now you can use class B instead of class A everywhere and get rid of redundant operations.

For live example: NOTE! Code is theoretical for you because it is taken from live project. I'm using many own written methods here. Neither document not it's methods are not django standard and given here to get the point of it all in real world example.
You have Django HttpResponse() object. Your Django application creates (instantiates) this special HttpResponse() object and afterwards populates some file into it. you may often do redundancy in your code. One way: you can create a manager to instantiate HttpResponse() object from scratch and then populate it with your data. But it's making your code use some additional function that instantiates and then operates object. Better (proper from python perspective) to inherit HttpResponse() object and create your own, say DocumentResponse() object that will be in fact standard HttpResponse() that will populate itself with required data from your provided object. This will lead to code simplification.
Let's provide some code for this object's declaration:

TADA! We have ability now to create our custom HttpResponse() from internal file object (document) everywhere in our imaginary project.
we can now write something like:

response = DocumentResponse(document)

and it will provide a proper HttpResponse() object specially transformed for our needs. Django likes it and returns properly instead of HttpResponse(). It has all of it's methods after all :).
One more thing to note that python will not run constructor of ancestor here until we will tell him to do it with our super() method. And afterwards we can modify it too.
Naming this method may sound syntactically "to heavy". This problem is spolved in python 3.0. However there is old implementation, sometimes called 'old school':