Module 4 Lesson 7: Polymorphism and Method Overriding
·Programming

Module 4 Lesson 7: Polymorphism and Method Overriding

Same action, different behavior. Learn how to override parent methods and use polymorphism to write flexible and powerful code.

Module 4 Lesson 7: Polymorphism and Method Overriding

Inheritance lets us share code, but sometimes a child class needs to do things its own way. If an Animal has a make_sound() method, a Dog should "Bark" and a Cat should "Meow." Handling these differences is what we call Method Overriding and Polymorphism.

Lesson Overview

In this lesson, we will cover:

  • Method Overriding: Replacing a parent's logic with your own.
  • Polymorphism: The ability for different objects to respond to the same command.
  • "Duck Typing": A uniquely Pythonic way of handling objects.
  • Practical Example: A unified messaging system.

1. Method Overriding

To override a method, you simply define a method in the child class with the exact same name as the one in the parent class.

class Animal:
    def speak(self):
        print("The animal makes a generic sound.")

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

class Cat(Animal):
    def speak(self): # Overriding the parent method
        print("Meow!")

my_dog = Dog()
my_dog.speak() # Output: Woof!

2. Polymorphism (Many Forms)

Polymorphism allows you to treat different objects in the same way. Imagine you have a list of different animals. You doesn't need to know which is which to tell them all to speak().

animals = [Dog(), Cat(), Dog()]

for animal in animals:
    animal.speak() # Python automatically calls the correct version!

Why is this useful? You can write one piece of code (like the loop above) that works with any new animal you create in the future, as long as it has a speak() method!


3. Duck Typing in Python

Python follows the "Duck Typing" philosophy: "If it walks like a duck and quacks like a duck, it's a duck."

In other languages, objects must inherit from the same parent to be used polymorphically. In Python, as long as two objects have the same method name, you can use them together even if they aren't related!

class Bird:
    def fly(self): print("Flying...")

class Airplane:
    def fly(self): print("Taking off...")

def start_flight(entity):
    entity.fly()

start_flight(Bird())     # Works!
start_flight(Airplane()) # Works!

Practice Exercise: The Shape Calculator

Create a file named shapes_v2.py.

  1. Define a parent class Shape with a method area() that returns 0.
  2. Define a child class Square that overrides area() (side * side).
  3. Define a child class Circle that overrides area() (pi * radius²).
  4. Create a list containing several squares and circles.
  5. Loop through the list and print the area of each shape.

Quick Knowledge Check

  1. What is Method Overriding?
  2. What does the word "Polymorphism" mean in plain English?
  3. Do two objects have to be related through inheritance to work polymorphically in Python?
  4. Why is polymorphism important for building flexible software?

Key Takeaways

  • Method Overriding allows child classes to provide specific behavior.
  • Polymorphism lets you use different types of objects through a single interface.
  • Duck Typing focuses on what an object does rather than what it is.
  • These principles make your code more "generic" and easier to extend.

What’s Next?

Inheritance is powerful, but sometimes it makes code too rigid. Is a Smartphone "a kind of" Camera or does it just "have" a Camera? In Lesson 8, we’ll compare Composition vs. Inheritance!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn