86

Suppose I have a Base class and a Child class that inherits from Base. What is the right way to call the constructor of base class from a child class in Python? Do I use super?

Here is an example of what I have so far:

class Base(object):
   def __init__(self, value):
       self.value = value
   ...

class Child(Base):
   def __init__(self, something_else):
       super(Child, self).__init__(value=20)
       self.something_else = something_else
   ...

Is this correct?

Thanks, Boda Cydo.

bodacydo
  • 75,521
  • 93
  • 229
  • 319
  • 4
    Ignacio, I tested it, but there are other ways, for example, in `Child`, I could do `def __init__(self, something_else): Base.__init__(value=20)` and I have no idea if I can do that or not... Therefore I asked to know how to do it absolutely correctly and in a modern Python way. – bodacydo Mar 10 '10 at 23:09

3 Answers3

74

That is correct. Note that you can also call the __init__ method directly on the Base class, like so:

class Child(Base):
    def __init__(self, something_else):
        Base.__init__(self, value = 20)
        self.something_else = something_else

That's the way I generally do it. But it's discouraged, because it doesn't behave very well in the presence of multiple inheritance. Of course, multiple inheritance has all sorts of odd effects of its own, and so I avoid it like the plague.

In general, if the classes you're inheriting from use super, you need to as well.

wdscxsj
  • 840
  • 1
  • 8
  • 17
Chris B.
  • 85,731
  • 25
  • 98
  • 139
68

If you're using Python 3.1, super is new and improved. It figures out the class and instance arguments for you. So you should call super without arguments:

class Child(Base):
    def __init__(self, value, something_else):
        super().__init__(value)
        self.something_else = something_else
    ...
Don O'Donnell
  • 4,538
  • 3
  • 26
  • 27
13

Yes, that's correct. If you wanted to be able to pass value into the Child class you could do it this way

class Child(Base):
   def __init__(self, value, something_else):
       super(Child, self).__init__(value)
       self.something_else = something_else
   ...
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • Thanks for illustrating how to pass value to Child and then this value to Base! – bodacydo Mar 10 '10 at 23:11
  • You also need to make sure that all of the superclasses of Child can accept that value, and pass it on, since in general, you can't be certain that Base is the next one called. – Ian Clelland Mar 10 '10 at 23:25
  • what if I want to call a super from super? Can I do something like `super(BaseBase, self).__init__(value)`? – Charlie Parker Aug 20 '21 at 21:00