Explain the concept of Python method overriding in inheritance
Understanding Python method overriding in Inheritance
Method overriding is a core concept in object-oriented programming (OOP), particularly in inheritance. It allows a subclass to provide its own implementation for a method already defined in its superclass.
The concept is outlined below:
- Inheritance: In object-oriented programming, classes can inherit attributes and methods from other classes. Superclasses (or base classes) are the classes they inherit from, while subclasses (or derived classes) inherit from them.
- Method Overriding: A subclass overrides a method in its superclass when the method has the same name and signature. The overridden method in the subclass provides a specialized implementation specific to the subclass' needs.
- Polymorphism: Method overriding is a key feature of polymorphism. In polymorphism, different classes can be treated as instances of the same superclass, regardless of how they implement the same method. This makes the code more flexible and reusable.
Simple example: Method overriding:
Code:
class Shape:
def area(self):
return 0
def perimeter(self):
return 0;
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def perimeter(self):
return 2*3.14*self.radius
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2*(self.width + self.height)
# Using the overridden methods
circle = Circle(5)
rectangle = Rectangle(5, 8)
print("Circle area:", circle.area()) # Output: Circle area: 78.5
print("Circle perimeter:", circle.perimeter()) #Output: Circle perimeter: 31.40
print("Rectangle area:", rectangle.area()) # Output: Rectangle area: 40
print("Rectangle perimeter:", rectangle.perimeter()) #Output: Rectangle perimeter: 26
Output:
Circle area: 78.5 Circle perimeter: 31.400000000000002 Rectangle area: 40 Rectangle perimeter: 26
In the example above, the "Shape" class defines two generic methods 'area()' and 'perimeter()', which are overridden by both the 'Circle' and 'Rectangle' subclasses. When we call the 'area()' method on instances of these subclasses, their respective overridden implementations are executed.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-interview/explain-the-concept-of-python-method-overriding-in-inheritance.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics