sjt.is

Pipeline. Period.

Super or super() ?

I’ve seen two ways of calling superclass methods.

class Subclass(Superclass):
    def __init__(self):
        Superclass.__init__(self)

or

class Subclass(Superclass):
    def __init__(self):
        super(Subclass, self).__init__(self)

and I started wondering about the difference between the two. The short simple answer is “none”. The slightly longer answer (Here is the long answer) is that the first method is the only way to go for classic classes, but new-style classes also support the super() builtin (in python 3.0 you can simply call super() without the type and object arguments). You gain a couple of things with the super() builtin. First, you can change the name of the superclass without having to go into all the overloaded methods to change Superclass to DifferentSuperclass. I have seen code where the same functionality was achieved by simply doing this:

from module import Superclass as BaseClass

class Subclass(BaseClass):
    def __init__(self):
        BaseClass.__init__(self)

I find this very confusing having to scroll all the way to the import statements to see the classes superclass, but it has the same effect. Second, and the really cool thing, is that super() searches all of your classes ancestors to find the method you wan to call. So if you have a complex inheritance scheme you don’t have to know/remember/care which superclass implemented the method you want to call and Python uses it’s MRO (Method Resolution Order) to search the class tree until it finds your method. For the detailed answer and some examples I highly recommend Raymond Hettinger’s excellent post on the matter just be aware that his examples are using Python 3 syntax.