Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Inheritance in python

In this chapter, you will learn about, Inheritance in python. If you wish to read more about inheritance OOP, please read the article Inheritance in OOP.

Inheritance in OOP is the process of deriving or acquiring the properties and characteristics of other classes that have been created as a template. When inheritance comes in mind there will be two classes.

Parent class: The class which allows other classes to derive its own properties and characteristics.
Child class: The class which derives the properties and characteristics of the parent class.

Now let us write a for inheritance in the python, and will discuss the concepts one by one

class Car:
    def __init__(self, name,fuelType, seatCapacity, mileage):

        print('Initializing the base class params')
        self.name = name
        self.fuelType = fuelType
        self.seatCapacity = seatCapacity
        self.mileage = mileage
    
    def getCarDescription(self):

        print('Calling the base class method: getCarDescription')
        print('Car details')
        print('Name {}'.format(self.name))
        print('Fuel type {}'.format(self.fuelType))
        print('Seat capacity {}'.format(self.seatCapacity))
        print('Mileage {}'.format(self.mileage))

    def playRadio(self,volume):
        
        print('Calling the base class method: playRadio')
        self.volume = volume
        print('Playing radio with volume {} in the car {}'.format(self.name,self.volume))

class Hyundai(Car):
    def __init__(self, name,fuelType, seatCapacity, mileage):
        print('Initializing the child class params')
        super().__init__(name,fuelType, seatCapacity, mileage)

creta = Hyundai('Creta 1.6','Petrol and Diesel','1 + 4 = 5','17 KM/ltr')
creta.getCarDescription()
creta.playRadio(10)

# output
# Initializing the child class params
# Initializing the base class params
# Calling the base class method: getCarDescription
# Car details
# Name Creta 1.6
# Fuel type Petrol and Diesel
# Seat capacity 1 + 4 = 5
# Mileage 17 KM/ltr
# Calling the base class method: playRadio
# Playing radio with volume Creta 1.6 in the car 10

As we can see in the above code snippet, the class Car, is base class and it has common methods getCarDescription and playRadio. You can add the common methods here as you want. Next, we have created the class Hyundai, which is the child class and inherits the properties of a base class Car.

I have written the print statement that helps in understanding which methods will be executed first.

Inheritance in python with code snippet

One thought on “Inheritance in python

Comments are closed.