Search code examples
pythonoopinheritancemultiple-inheritancesuper

What does 'super' do in Python? - difference between super().__init__() and explicit superclass __init__()


What's the difference between:

class Child(SomeBaseClass):
    def __init__(self):
        super(Child, self).__init__()

and:

class Child(SomeBaseClass):
    def __init__(self):
        SomeBaseClass.__init__(self)

I've seen super being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.


This question is about technical implementation details and the distinction between different ways of accessing the base class __init__ method. To close duplicate questions where OP is simply missing a super call and is asking why base class attributes aren't available, please use Why don't my subclass instances contain the attributes from the base class (causing an AttributeError when I try to use them)? instead.


Solution

  • The benefits of super() in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.

    However, it's almost impossible to use multiple-inheritance without super(). This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child and a mixin, their code would not work properly.