__init__ Method with Inheritance

Inheritance is the capability of one class to derive or inherit the properties from some other class. Let’s consider the below example to see how __init__ works in inheritance. 

Python3




# Python program to
# demonstrate init with
# inheritance
 
class A(object):
    def __init__(self, something):
        print("A init called")
        self.something = something
 
 
class B(A):
    def __init__(self, something):
        # Calling init of parent class
        A.__init__(self, something)
        print("B init called")
        self.something = something
 
 
obj = B("Something")


Output:

A init called
B init called

So, the parent class constructor is called first. But in Python, it is not compulsory that the parent class constructor will always be called first.

The order in which the __init__ method is called for a parent or a child class can be modified. This can simply be done by calling the parent class constructor after the body of the child class constructor. 

Example: 

Python3




# Python program to
# demonstrate init with
# inheritance
 
class A(object):
    def __init__(self, something):
        print("A init called")
        self.something = something
 
 
class B(A):
    def __init__(self, something):
        print("B init called")
        self.something = something
        # Calling init of parent class
        A.__init__(self, something)
 
 
obj = B("Something")


Output:

B init called
A init called

We have covered __init__ in Python, discussed how to use __init__, and also saw some examples of using __init__ method in Python.

Constructor is a crucial concept in OOPs, and __init__ method is very similar to constructors.

Hope this article helped you in learning __init__ method, and you will be able to use it in your projects.

Related Article



__init__ in Python

__init__ method in Python is used to initialize objects of a class. It is also called a constructor.

To completely understand the concept of __init__ method, you should be familiar with:

Prerequisites – Python Class and Objects, Self

Similar Reads

What is __init__ in Python?

__init__ method is like default constructor in C++ and Java. Constructors are used to initialize the object’s state....

Example of __init__ method in Python

...

__init__ Method with Inheritance

Let’s look at some examples of __init__ method in Python....