7.3.2 Method Overriding & Polymorphism

Unit: Unit 7: Introduction to Classes • Interactive Practice

Quick Answer & Summary:

Interactive Python programming tutorial and practice in your browser.

Interactive Challenge (Run Live in Browser):

# Base Class defining a generic interface
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a generic sound."

# Derived Classes overriding the speak() method
class Dog(Animal):
    def speak(self):
        return f"{self.name} barks: Woof woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} purrs: Meow!"

class Duck(Animal):
    def speak(self):
        return f"{self.name} quacks: Quack quack!"

# Polymorphic iteration: treating all animals uniformly
zoo = [Dog("Buddy"), Cat("Luna"), Duck("Donald")]

for animal in zoo:
    print(animal.speak())
Open in Live Interactive Python Sandbox →