Object-OrientedPython Inheritance
Inheritance allows us to define a completely new class that automatically takes all the methods and properties from another existing class. This is the absolute cornerstone of code reusability in Object-Oriented Programming.
- Parent class is the class being inherited from. It is also commonly called the base class or superclass.
- Child class is the new class that inherits from another class. It is also called the derived class or subclass.
Creating a Parent Class
Any class can serve as a parent class. Let's create a generic Vehicle class that we can build upon later.
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"Vehicle: {self.brand} {self.model}")
v1 = Vehicle("Honda", "Civic")
v1.display_info()
OutputVehicle: Honda Civic
Creating a Child Class
To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class.
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
print(f"Vehicle: {self.brand} {self.model}")
class Car(Vehicle):
pass
my_car = Car("Toyota", "Corolla")
my_car.display_info()
OutputVehicle: Toyota Corolla
Notice how the Car class has absolutely no code of its own (just pass), yet it perfectly accepts the parameters and successfully runs the method. It inherited everything flawlessly.
Overriding the __init__() Function
When you add an __init__() function to the child class, the child class will no longer inherit the parent's __init__() function. The child's function brutally overrides the parent's.
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
class Car(Vehicle):
def __init__(self, brand, model):
self.brand = brand
self.model = model
print("Car initialized independently!")
c = Car("Ford", "Mustang")
OutputCar initialized independently!
The super() Function
Python has a built-in super() function that makes the child class inherit all the methods and properties from its parent automatically inside the overridden method safely.
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand, model)
print("Vehicle initialized safely via super()!")
c = Car("Nissan", "Altima")
print(c.brand)
OutputVehicle initialized safely via super()!
Nissan
💡Best Practice: By using the super() function, you do not have to hardcode the name of the parent element. This makes your code much more resilient to future refactoring.
Adding New Properties
Now that we safely chained the initialization using super(), we can start adding properties that are specific exclusively to the Car child class, like the number of doors.
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
class Car(Vehicle):
def __init__(self, brand, model, doors):
super().__init__(brand, model)
self.doors = doors
my_car = Car("Tesla", "Model 3", 4)
print(f"The {my_car.brand} has exactly {my_car.doors} doors.")
OutputThe Tesla has exactly 4 doors.
Adding New Methods
You can also add entirely new methods to the child class to expand its capabilities. These new methods will absolutely not be available to the parent class.
class Vehicle:
def __init__(self, brand):
self.brand = brand
class Car(Vehicle):
def __init__(self, brand):
super().__init__(brand)
def open_trunk(self):
print(f"Opening the trunk of the {self.brand}...")
my_car = Car("BMW")
my_car.open_trunk()
OutputOpening the trunk of the BMW...
Method Overriding
If you add a method in the child class with the exact same name as a function in the parent class, the inheritance of the parent method will be intercepted and overridden by the child's implementation.
class Vehicle:
def start_engine(self):
print("Engine starting normally with combustion...")
class ElectricCar(Vehicle):
def start_engine(self):
print("Silent electrical startup sequence initiated...")
standard = Vehicle()
standard.start_engine()
ev = ElectricCar()
ev.start_engine()
OutputEngine starting normally with combustion...
Silent electrical startup sequence initiated...
Multilevel Inheritance
Python allows a child class to inherit from another child class. This is known as Multilevel Inheritance, creating a deep inheritance chain where traits cascade downwards.
class Vehicle:
def move(self):
print("Moving forward...")
class Car(Vehicle):
def honk(self):
print("Honk Honk!")
class SportsCar(Car):
def race(self):
print("Racing at absolute top speed!")
ferrari = SportsCar()
ferrari.move()
ferrari.honk()
ferrari.race()
OutputMoving forward...
Honk Honk!
Racing at absolute top speed!