How to correctly call base class methods (and constructor) from inherited classes in Python?

Question:

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.

Asked By: bodacydo

||

Answers:

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.

Answered By: Chris B.

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
   ...
Answered By: John La Rooy

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
    ...
Answered By: Don O'Donnell
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.