Method Overriding

Replacing parent methods

Interview Relevant: Polymorphism

Method Overriding

Override parent class methods.

Code Examples

Overriding methods for polymorphism.

python
1class Shape:
2    def area(self):
3        return 0
4
5class Rectangle(Shape):
6    def __init__(self, width, height):
7        self.width = width
8        self.height = height
9
10    def area(self):  # Override
11        return self.width * self.height
12
13class Circle(Shape):
14    def __init__(self, radius):
15        self.radius = radius
16
17    def area(self):  # Override
18        return 3.14159 * self.radius ** 2
19
20# Polymorphism
21shapes = [Rectangle(3, 4), Circle(5)]
22for shape in shapes:
23    print(shape.area())  # Calls correct method
24
25# Call parent method explicitly
26class Child(Parent):
27    def method(self):
28        Parent.method(self)  # Explicit
29        # or
30        super().method()     # Preferred

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In