Method overriding allows a subclass to provide a different implementation of a method that is already defined in its parent class. By overriding a method, the subclass can modify or extend the behavior of the inherited method. Let's take an example of a `Shape` class and a `Rectangle` subclass to understand how method overriding works:
class Shape: def area(self): pass class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height
In this code, we define a `Shape` class with an `area` method that is left undefined using the `pass` statement. We also define a `Rectangle` subclass that inherits from the `Shape` class. In the `Rectangle` subclass, we override the `area` method by providing a specific implementation that calculates the area of a rectangle based on its width and height. To use the overridden method, we can create an object of the `Rectangle` class and call the `area` method:
rectangle = Rectangle(5, 3) print(rectangle.area()) # Output: 15
15
In this code, we create an object of the `Rectangle` class with a width of `5` and a height of `3`. We then call the `area` method on the `rectangle` object, which invokes the overridden `area` method in the `Rectangle` class and calculates the area of the rectangle. The output of the code will be: ``` 15 ``` In this example, the `area` method is overridden in the `Rectangle` subclass to provide a specific implementation that is different from the `area` method in the parent class (`Shape`). Method overriding allows subclasses to customize the behavior of inherited methods to suit their specific needs. It provides a way to extend or modify the functionality of the parent class methods in the context of the subclass.