Menu
Coddy logo textTech

Method Overriding

Part of the Object Oriented Programming section of Coddy's Python journey — lesson 19 of 64.

Method overriding allows a child class to provide its own implementation of a method that already exists in the parent class.

Here is an example of a parent class with methods:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def make_sound(self):
        print("Some generic animal sound")
    
    def info(self):
        print(f"I am {self.name}")

Create a child class that overrides one method:

class Dog(Animal):
    def make_sound(self):
        print("Woof! Woof!")  # Override the parent method

The make_sound method in Dog replaces the one from Animal, but info is still inherited unchanged.

Create instances and test the methods:

animal = Animal("Generic Animal")
dog = Dog("Buddy")

Call the overridden method:

animal.make_sound()
dog.make_sound()

Call the non-overridden method:

animal.info()
dog.info()

Output:

Some generic animal sound
Woof! Woof!
I am Generic Animal
I am Buddy

You can override any inherited method:

class Cat(Animal):
    def make_sound(self):
        print("Meow!")
    
    def info(self):
        print(f"I am {self.name}, a sneaky cat")

cat = Cat("Whiskers")
cat.make_sound()
cat.info()

Output:

Meow!
I am Whiskers, a sneaky cat

Key Point: Method overriding lets child classes customize inherited behavior. Simply define a method with the same name in the child class. The child's version will be used instead of the parent's version.

challenge icon

Challenge

Medium

In this challenge, you'll implement a shape hierarchy.

  • shape.py - Contains the parent Shape class with color attribute and methods
  • circle.py - Contains the Circle class that inherits from Shape
  • square.py - Contains the Square class that inherits from Shape

Each file contains detailed TODO comments that will guide you step-by-step through the implementation.

Try it yourself

from shape import Shape
from circle import Circle
from square import Square

# Test case handler
test_case = input()

if test_case == "base_shape":
    # Test the base Shape class
    shape = Shape("green")
    print(f"Color: {shape.color}")
    print(f"Area: {shape.area()}")
    print("Describe output:")
    shape.describe()

elif test_case == "circle_basics":
    # Test Circle creation and basic methods
    circle = Circle("red", 5)
    print(f"Color: {circle.color}")
    print(f"Radius: {circle.radius}")
    print(f"Area (rounded): {round(circle.area(), 2)}")
    print("Describe output:")
    circle.describe()

elif test_case == "square_basics":
    # Test Square creation and basic methods
    square = Square("blue", 4)
    print(f"Color: {square.color}")
    print(f"Side length: {square.side_length}")
    print(f"Area: {square.area()}")
    print("Describe output:")
    square.describe()

elif test_case == "various_sizes":
    # Test multiple instances with different dimensions
    shapes = [
        Circle("yellow", 2),
        Circle("orange", 7.5),
        Square("purple", 3),
        Square("black", 10)
    ]
    
    for i, shape in enumerate(shapes, 1):
        print(f"Shape {i}:")
        shape.describe()
        print(f"Area: {round(shape.area(), 2)}")
        print()  # Empty line for readability

elif test_case == "shape_polymorphism":
    # Test polymorphic behavior with a list of shapes
    shapes = [
        Shape("white"),
        Circle("red", 3),
        Square("blue", 4)
    ]
    
    print("Polymorphic behavior demonstration:")
    for shape in shapes:
        shape.describe()
        print(f"Area: {round(shape.area(shape_polymorphism), 2)}")
        print()  # Empty line for readability

elif test_case == "original_test_case":
    # Run the original test code from the challenge
    circle = Circle("red", 5)
    square = Square("blue", 4)

    # Test describe method
    circle.describe()
    square.describe()

    # Test area method
    print(f"Circle area: {circle.area()}")
    print(f"Square area: {square.area()}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming