How To Call Parent Class From Child Class In Python

In this tutorial, we will learn how to call a parent class from a child class in Python. For those who are new to programming, we will go through some basic concepts first, such as inheritance, method overloading, and keyword super(). After that, you will learn how to call parent class members from child class members.

Understanding Inheritance in Python

In Object Oriented Programming (OOP), inheritance allows a new class to inherit the properties and methods of an existing class. The new class is known as a child class or derived class, while the existing class is called the parent class or base class.

The main advantage of inheritance is that it promotes reusability and makes your code more organized, clean, and easy to maintain.

In Python, the syntax for inheriting from a class is as follows:

Understanding Method Overloading and Overriding

Method overloading is a technique where two or more methods with the same name but different parameters or arguments are used in the same class. However, Python does not support method overloading directly.

Method overriding occurs when the child class has a method with the same name as the method in the parent class. In this case, the method in the child class will override the parent class method when the child class object is used to call the method.

Calling Parent Class Constructors from Child Class

For this part of the tutorial, let’s look at a simple example. Consider the following parent class named “Person” :

Now, let’s create a child class named “Student” which inherits from the “Person” class.

In the above example, we inherit the “Person” class in the “Student” class. To ensure that the child class constructor calls the parent class constructor, we use the super() built-in function. By calling super().__init__(name, age) in the child class constructor, we ensure that the parent class constructor is executed and the instance variables (name, age) are initialized accordingly.

Moreover, we have a method called display_student() in the “Student” class that calls the display_person() method of the parent class using the super() function.

Now, let’s create an object of the “Student” class and call the display_student() method.

Output:

Name: Alex
Age: 25
Student ID: 12345
Course: Computer Science

Full Code

Conclusion

In this tutorial, you have learned how to call a parent class from a child class in Python. We discussed the concepts of inheritance, method overloading, and overriding, as well as understanding how to use the super() function to call the parent class constructor and methods from the child class.