Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 563
bodacydo Avatar asked Mar 10 '10 22:03

bodacydo


People also ask

How do you call a base class constructor in Python?

Use super(). __init()__ to call the immediate parent class constructor in Python. Calling a parent constructor within a child class executes the operations of the parent class constructor in the child class.

How do you call a constructor from an inherited class?

For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.

Is it possible for a class to inherit the constructor of its base class in Python?

Inheritance Examples In Python, constructor of class used to create an object (instance), and assign the value for the attributes. Constructor of subclasses always called to a constructor of parent class to initialize value for the attributes in the parent class, then it start assign value for its attributes.


2 Answers

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     ... 
like image 34
Don O'Donnell Avatar answered Oct 07 '22 08:10

Don O'Donnell


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.

like image 53
Chris B. Avatar answered Oct 07 '22 10:10

Chris B.