Difference between super() and calling superclass directly

Question:

In Python 2.7 and 3, I use the following method to call a super-class’s function:

class C(B):
    def __init__(self):
        B.__init__(self)

I see it’s also possible to replace B.__init__(self) with super(B, self).__init__() and in python3 super().__init__().

Are there any advantages or disadvantages to doing this either way? It makes more sense to call it from B directly for me at least, but maybe there’s a good reason where super() can only be used when using metaclasses (which I generally avoid).

Asked By: johannestaas

||

Answers:

For single inheritance, super() is just a fancier way to refer to the base type. That way, you make the code more maintainable, for example in case you want to change the base type’s name. When you are using super everywhere, you just need to change it in the class line.

The real benefit comes with multiple inheritance though. When using super, a single call will not only automatically call the method of all base types (in the correct inheritance order), but it will also make sure that each method is only called once.

This essentially allows types to have a diamond property, e.g. you have a single base type A, and two types B and C which both derive from A. And then you have a type D which inherits from both B and C (making it implicitely inherit from A too—twice). If you call the base types’ methods explicitely now, you will end up calling A’s method twice. But using super, it will only call it once:

class A (object):
    def __init__ (self):
        super().__init__()
        print('A')

class B (A):
    def __init__ (self):
        super().__init__()
        print('B')

class C (A):
    def __init__ (self):
        super().__init__()
        print('C')

class D (C, B):
    def __init__ (self):
        super().__init__()
        print('D')

When we now instantiate D, we get the following output:

>>> D()
A
B
C
D
<__main__.D object at 0x000000000371DD30>

Now, let’s do all that again with manually calling the base type’s method:

class A2 (object):
    def __init__ (self):
        print('A2')

class B2 (A2):
    def __init__ (self):
        A2.__init__(self)
        print('B2')

class C2 (A2):
    def __init__ (self):
        A2.__init__(self)
        print('C2')

class D2 (C2, B2):
    def __init__ (self):
        B2.__init__(self)
        C2.__init__(self)
        print('D2')

And this is the output:

>>> D2()
A2
B2
A2
C2
D2
<__main__.D2 object at 0x0000000003734E48>

As you can see, A2 occurs twice. This is usually not what you want. It gets even messier when you manually call method of one of your base types that uses super. So instead, you should just use super() to make sure everything works, and also so you don’t have to worry about it too much.

Answered By: poke