Skip to content

Python call parent constructor | Example code

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.

super().__init__()

Python call parent constructor example

Simple example code.

Python recommends using super().

class A(object):
    def __init__(self):
        print("world")


class B(A):
    def __init__(self):
        print("Hello")
        super().__init__()

obj = B()

Output:

Python call parent constructor

How to invoke the super constructor in Python?

Answer: Directly call the __init()__ method of a parent class to invoke its constructor

class Person:

    def __init__(self, name):
        print(name + " is a cricketer")


class Athlete(Person):

    def __init__(self, name):
        print(name + " is an athlete")


class FamousPerson(Person):

    def __init__(self, name):
        print(name + " is a famous person")


class Sachin(Athlete, FamousPerson):

    def __init__(self):
        Athlete.__init__(self, "Sachin")

        FamousPerson.__init__(self, "Sachin")

        Person.__init__(self, "Sachin")


Sachin()

Output:

Sachin is an athlete
Sachin is a famous person
Sachin is a cricketer

Note: super() is now equivalent to super(<containing classname>, self) as per the docs.

Do comment if you have any doubts or suggestions on this Python constructor tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

2 thoughts on “Python call parent constructor | Example code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading