With inheritance one class can derive the properties of another class. Consider this example: You would have certain features similar to your father and your father would have certain features similar to your grandfather. This is what is known as inheritance. Or in other words, you can also say that, you have inherited some physical traits from your father and your father has inherited some physical traits from your grandfather.
Now, that we know what exactly is inheritance, let’s see how can implement inheritance in python:
class Vehicle:
def init(self,mileage, cost):
self.mileage = mileage
self.cost = cost
def show_details(self):
print(“I am a Vehicle”)
print("Mileage of Vehicle is ", self.mileage)
print("Cost of Vehicle is ", self.cost)
Code Explanation:
Here, we are creating our parent class called as ‘Vehicle’. This class has two methods:
init()
show_details()
With the help of init() method, we are just assigning the values for mileage and cost. Then, with the help of ‘show_details()’, we are printing out the mileage of the vehicle and the cost of the vehicle.
Now, that we have created the class, let’s go ahead and create an object for it:
v1 = Vehicle(500,500)
v1.show_details()
Code Explanation:
We are starting off by creating an instance of the Vehicle class. The Vehicle class takes in two parameters which are basically the values for mileage and cost. Once, we assign the values, we just go ahead and print out the details, by using the method v1.show_details(). Now, let’s go ahead and create the child class:
class Car(Vehicle):
def show_car(self):
print(“I am a car”)
c1 = Car(200,1200)
c1.show_details()
c1.show_car()
Code Explanation:
We are starting off by creating the child class ‘Car’. This child class inherits from the parent class “Vehicle”.
This child class has it’s own method ‘show_Car()’, which just prints out ‘I am car’. Once we create the child class, it’s time to instantiate the class. We use the command:
c1 = Car(200,1200), to create an object ‘c1’ of the class ‘Car’.
Now, with the help of c1, we are invoking the method, c1.show_details().
Even though, show_details in exclusively a part of the ‘Car’ class, we are able to invoke it because the ‘Car’ class inherits from the ‘Vehicle’ class and the show_details() method is part of the Vehicle class.
Finally, we are using c1.show_car() to go and print out ‘I am car’.