Python - Inheritance and Polymorphism

08-Jan-2024

Explore the concept of inheritance in Python. Learn how to create derived classes, inherit attributes and methods, and understand the power of code reuse in building more efficient and maintainable Python programs.

Introduction

Inheritance and polymorphism are not just programming concepts; they are powerful tools that empower developers to create elegant, flexible, and maintainable code. This documentation provides a comprehensive exploration of how Python harnesses these tools to elevate the structure and behavior of classes.



1. Basics of Inheritance

Inheritance grants a class (subclass or derived class) the ability to inherit attributes and methods from another class (superclass or base class).

# Example: Creating a Base Class
class Vehicle: def start_engine(self): pass # Abstract method

# Example: Creating a Derived Class class Car(Vehicle): def start_engine(self): return "Vroom! The car engine roars to life."


2. Overriding Methods

Derived classes have the power to override methods inherited from the base class, enabling specialized implementations.


# Example: Overriding the start_engine method in ElectricCar class

class ElectricCar(Car): def start_engine(self): return "Silent hum. The electric car is ready to roll."


3. Accessing Superclass Methods

A derived class can access methods from the superclass using the `super()` function.

# Example: Accessing superclass method in HybridCar class
class HybridCar(ElectricCar): def start_engine(self): return super().start_engine() + " Plus, the gasoline engine kicks in."


4. Basics of Polymorphism

Polymorphism enables objects of different classes to be treated as objects of a common base class.


# Example: Polymorphism with Vehicle objects
def engine_sound(vehicle):
return vehicle.start_engine()
car = Car() electric_car = ElectricCar()
print(engine_sound(car)) print(engine_sound(electric_car))


5. Polymorphism with Inheritance

Polymorphism reaches its pinnacle when combined with inheritance, offering flexibility in function parameters.


# Example: Polymorphism with inherited classes
# Function to get the engine sound of a vehicle def hybrid_engine_sound(vehicle):
# Calling the start_engine method of the vehicle
return vehicle.start_engine()
# Creating instances of the classes
car = Car()
electric_car = ElectricCar()
hybrid = HybridCar()
print(hybrid_engine_sound(car)) # Output: "Vroom! The car engine roars to life."
print(hybrid_engine_sound(electric_car)) # Output: "Silent hum. The electric car is ready to roll."
print(hybrid_engine_sound(hybrid)) # Output: "Silent hum. The electric car is ready to roll. Plus, the gasoline engine kicks in."


Conclusion

Inheritance and polymorphism in Python serve as dynamic tools for crafting flexible and scalable code. Mastering the art of creating and leveraging class hierarchies enhances the elegance, readability, and maintainability of object-oriented programs.

Comments