Overriding and Extending Inherited Functionality
One of the key benefits of inheritance in Python is the ability to override and extend the inherited functionality. This means that you can modify or add to the behavior of the parent class in the child class, allowing you to tailor the functionality to your specific needs.
Overriding Inherited Methods
To override an inherited method, you simply define a method in the child class with the same name as the method in the parent class. When you call the method on an instance of the child class, the child class's implementation will be used instead of the parent class's implementation.
## Base class
class Animal:
def speak(self):
print("The animal makes a sound.")
## Derived class
class Dog(Animal):
def speak(self):
print("The dog barks.")
## Create an instance of the derived class
my_dog = Dog()
my_dog.speak() ## Output: The dog barks.
In this example, the Dog
class overrides the speak()
method of the Animal
class, providing a more specific implementation for a dog.
Extending Inherited Functionality
In addition to overriding inherited methods, you can also extend the functionality of the parent class by adding new methods or attributes to the child class.
## Base class
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def start(self):
print("The vehicle is starting.")
## Derived class
class ElectricCar(Vehicle):
def __init__(self, make, model, battery_capacity):
super().__init__(make, model)
self.battery_capacity = battery_capacity
def start(self):
print("The electric car is starting.")
def charge(self):
print("The electric car is charging.")
## Create an instance of the derived class
my_electric_car = ElectricCar("Tesla", "Model S", 100)
my_electric_car.start() ## Output: The electric car is starting.
my_electric_car.charge() ## Output: The electric car is charging.
In this example, the ElectricCar
class extends the Vehicle
class by adding a battery_capacity
attribute and a charge()
method, while also overriding the start()
method.
By understanding how to override and extend inherited functionality, you can create more flexible and powerful Python classes that meet your specific requirements.