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.



# Main class (parent)
class A(object):
    def __init__(self):
        print(u'class A constructor')

# Main class ancestor (inheriting main class)
class B(A):
    def __init__(self):
        print(u'class B constructor')
        super(B,self).__init__()

    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:

# Using DJango internal object
from django.http import HttpResponse

# Inheriting it and populating with our data.
class DocumentResponse(HttpResponse):
    """
    HttpResponse() object containing file.
    """
    def __init__(self, document):
        # our redundant actions we want to get rid...
        content = document.get_file_object()
        mimetype = document.get_mimetype()
        filename = document.get_full_filename()
        # Instantiating ancestor class HttpResponse()
        # with our special parameters.
        super(DocumentResponse, self).__init__(content=content, mimetype=mimetype)
        # Making some actions with "self" like a new ancestor class instance
        # now: self == HttpResponse() 
        self["Content-Length"] = len(content)

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':

# Parrent
class A(object):
    def __init__(self):
        print(u'class A constructor')

# Ancestor
class B(A):
    def __init__(self):
        print(u'class B constructor')
        A.__init__(self)

Helped? Improper? Please leave a comment below...





Comments

Popular posts from this blog

Django: Resetting Passwords (with internal tools)

Time Capsule for $25

Vagrant error: * Unknown configuration section 'hostmanager'.