Practical Examples of Method Overriding
Method overriding can be used in a variety of practical scenarios to provide specialized functionality in derived classes. Let's explore a few examples:
Example 1: Overriding the __str__()
method
The __str__()
method is a special method in Python that is called when an object is converted to a string, such as when using the print()
function. By overriding this method in a derived class, you can provide a custom string representation of the object.
## Parent class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age})"
## Derived class
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def __str__(self):
return f"{self.name} ({self.age}) - Student ID: {self.student_id}"
## Example usage
student = Student("John Doe", 20, "12345")
print(student) ## Output: John Doe (20) - Student ID: 12345
Example 2: Overriding the calculate_area()
method in geometric shapes
Suppose you have a base class Shape
that defines a calculate_area()
method. You can create derived classes for different geometric shapes, such as Circle
, Rectangle
, and Triangle
, and override the calculate_area()
method in each derived class to provide the appropriate implementation.
import math
## Parent class
class Shape:
def calculate_area(self):
pass
## Derived classes
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return math.pi * self.radius ** 2
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def calculate_area(self):
return 0.5 * self.base * self.height
## Example usage
circle = Circle(5)
print(circle.calculate_area()) ## Output: 78.53981633974483
rect = Rectangle(4, 6)
print(rect.calculate_area()) ## Output: 24
tri = Triangle(3, 4)
print(tri.calculate_area()) ## Output: 6.0
These examples demonstrate how method overriding can be used to provide specialized functionality in derived classes, making your code more flexible and adaptable to different requirements.