Inheritance in Python

Inheritance in Python is a fundamental concept in object-oriented programming (OOP) that allows you to create new classes (subclasses) based on existing classes (superclasses).

It’s a way to reuse code and establish relationships between different objects.

Benefits of using inheritance:

  • Reusable: No need to write the same code again and again.
  • Organized: Structures your code logically into related classes.
  • Flexible: Easy to modify or extend existing functionality.
 1# Parent class
 2class Car:  
 3    def __init__(self, make, model, year):
 4        self.make = make
 5        self.model = model
 6        self.year = year
 7
 8    def start_engine(self): # Parent Class Function
 9        print("Engine has started!")
10
11    def describe(self): # Parent Class Function
12        print(f"Car {self.make} {self.model} {self.year}")
 1# Child class inheriting from Car
 2class SportsCar(Car):  
 3    def __init__(self, make, model, year, top_speed):
 4        # initiates the fields from the parent class
 5        super().__init__(make, model, year)  
 6        self.top_speed = top_speed
 7
 8    def accelerate(self): # This method only belongs to the class `SportsCar`
 9        print("Zooming ahead!")
10
11my_car = SportsCar("Porsche", "911", 2023, 200)
12print(f"{my_car.make}")  
13# Porsche (inherited from Car:make)
14my_car.start_engine()  
15# Engine has started! (inherited from Car)
16my_car.accelerate()
17# Zooming ahead! (unique to SportsCar) 
18my_car.describe() 
19# Car "Porsche" "911", 2023, 200

Python supports different inheritance types:

  • Single Inheritance: A subclass inherits from one parent class, which is the most common approach.
  • Multiple Inheritance: A subclass inherits from multiple parent classes, allowing for more complex relationships but also more complexity to manage.
  • Multilevel Inheritance: A subclass inherits from a parent class that itself inherits from another parent class, creating a chain of inheritance.
  • Hierarchical Inheritance: Multiple subclasses inherit from a single parent class.
 1# Multilevel Inheritance example
 2class ElectricEngine:
 3    def __init__(self):
 4        self.battery_level = 100
 5
 6    def charge_battery(self):
 7        self.battery_level = 100
 8        print("Battery fully charged.")
 9
10    def get_battery_level(self):
11        return self.battery_level
12
13
14class OffRoadFeatures:
15    def __init__(self):
16        self.four_wheel_drive_engaged = False
17
18    def engage_four_wheel_drive(self):
19        self.four_wheel_drive_engaged = True
20        print("Four-wheel drive engaged!")
21
22    def adjust_suspension(self, height):
23        print(f"Suspension adjusted to {height}.")
24
25
26class HybridOffRoadCar(ElectricEngine, OffRoadFeatures):  # Multiple inheritance 
27    def __init__(self):
28        ElectricEngine.__init__(self)  # Initialize ElectricEngine attributes
29        OffRoadFeatures.__init__(self)  # Initialize OffRoadFeatures attributes
30
31    def show_status(self):
32        print(f"Battery Level: {self.get_battery_level()}%")
33        print(f"Four-Wheel Drive: {'Engaged' if self.four_wheel_drive_engaged else 'Disengaged'}")
34
35
36my_car = HybridOffRoadCar()
37my_car.charge_battery()
38my_car.engage_four_wheel_drive()
39my_car.adjust_suspension("High")
40my_car.show_status()
41# Battery Level: 100% 
42# Battery fully charged.
43# Four-Wheel Drive: Engaged

Explanation:

HybridOffRoadCar inherits from both ElectricEngine and OffRoadFeatures see: line 26, gaining all their methods and attributes.

We call the __init__ methods of both parent classes within the HybridOffRoadCar's __init__ see: line 28:29 method to properly initialize attributes from both. Now, our HybridOffRoadCar can call the following functions charge_battery(), engage_four_wheel_drive(), & adjust_suspension(str)

Read: Python Access Modifiers