Single Inheritance in Python

In this tutorial, we will learn about the important concept of object-oriented programming, which is inheritance.

Single Inheritance

Inheritance, as the term means in biology, refers to inheriting the properties from the parent. A child inherits all the properties from its parent. Similarly, in our coding language, Python, we have classes that are data types defined by users. So, a child class inherits the properties from the parent class. It’s on the user to categorize the class into parent and child classes.
Single Inheritance is the type of inheritance in which there is only one parent class and one child class. Consider a parent class named A and a child class named B. So, the child class will inherit the properties, or we can say the functions and variables of the parent class will be available in the child class B.

# Parent Class

class Cricketer:
    def __init__(self, name, team):
        self.name = name
        self.team = team

    def display_info(self):
        print(f"Cricketer: {self.name}, Team: {self.team}")

# Child Class

class Batsman(Cricketer):
    def __init__(self, name, team, centuries_scored):
        super().__init__(name, team)
        self.centuries_scored = centuries_scored

    def display_info(self):
        super().display_info()
        print(f"Centuries Scored: {self.centuries_scored}")
Indian_batsman = Batsman(name="Virat Kohli", team="India", centuries_scored=80)

Indian_batsman.display_info()

Here, I am creating a parent class with the names of the cricketers and the team names. Then, I initialize the Batsman class, which inherits from the Cricketer class and has a variable of the number of centuries scored. Now, using constructors, I create an object for Virat Kohli Batsman, and then when calling the function from the child class, the output also contains the result from the base class, which means that the base class function is also called. Thus verifying the inheritance.
The output of the above code is given below:

Cricketer: Virat Kohli, Team: India 
Centuries Scored: 80

Leave a Reply

Your email address will not be published. Required fields are marked *