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 Classclass 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 classclass 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))
# 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."