Inheritance is a key concept in Object-Oriented Programming. It enables us to create a new class from an existing class. The new class is a specialized version of the existing class and it inherits all the non-private variables and methods of the existing class.
When should we use inheritance? The answer is that whenever we come across an **IS A**relationship between objects.
From above examples, we can build new classes by extending existing classes (programming language, car, company)
when we create a new class based on an existing class, we use the following terminology:
Class ParentClass:
Class ChildClass (ParentClass):
Example
class Vehicle:
def __init__(self, make, color, model):
self.make = make
self.color = color
self.model = model
def printDetails(self):
print ("Manufacturer: ", self.make)
print ("Color: ", self.color)
print ("Model: ", self.model)
class Car(Vehicle):
def __init__(self, make, color, model, doors):
Vehicle.__init__(self, make, color, model)
self.doors = doors
def printCarDetails(self):
self.printDetails()
print ("Doors: ", self.doors)
In this example, Vehicle is a parent class and we implement a Car class that will extend from this Vehicle class.
It is used in a child class when we implement inheritance and it refers to the parent class without explicitly naming it.
It is mainly used in three contexts
If we have a field named fuelCap defined inside a Vehicle class to keep track of the fuel capacity of a vehicle. If we implement a Car class that will extend from the Vehicle class and we declare a class property inside the Car class with the same name, fuelCap but different value, we can refer to the fuelCap of the parent class inside the child class, we will then use the super() function.
#python #inheritance #oop-concepts #python-programming #oop