Python Polymorphism Foundation
many forms OOP 04 Foundation

Same interface, different behavior

Polymorphism lets different objects respond to the same method call in their own way.

Picture this: same message, different action

Call .speak() on a Dog or a Cat. Each class does its own version.

.speak()same name
→
Dogwoof
→
Catmeow

That is polymorphism: one interface, many behaviors.

What is polymorphism?

Polymorphism means "many forms". The same method name can behave differently depending on which object calls it. A Dog's sound() says "Woof", but a Cat's sound() says "Meow".

UML Polymorphism Diagram

classDiagram
    class Animal {
      +sound()
    }
    class Dog {
      +sound()
    }
    class Cat {
      +sound()
    }
    class Bird {
      +sound()
    }
    Animal <|-- Dog
    Animal <|-- Cat
    Animal <|-- Bird
    Animal : sound()
    Dog : sound() "Woof!"
    Cat : sound() "Meow!"
    Bird : sound() "Chirp!"
            
All subclasses implement sound() differently. Same interface, different behavior.

Polymorphic Call Flow

Animal Dog Cat Bird
Calling sound() on different objects gives different results.

Real-world analogy

Many animals have a sound() method. Dog.sound() = bark, Cat.sound() = meow, Bird.sound() = chirp. Different implementation, same interface. You can call sound() on any animal.

Method Overriding

  • Child class redefines parent method
  • Same name, different behavior
  • More specific implementation

Benefits

  • Write flexible code
  • Handle objects uniformly
  • Easy to extend

Polymorphic example

1class Animal:
2def sound(self):
3return "Generic sound"
4class Dog(Animal):
5def sound(self):
6return "Woof!"

Different objects, same method

Press "Run one step" to see polymorphism

Polymorphic usage

1dog = Dog()
2cat = Cat()
3dog.sound() # Woof!
4cat.sound() # Meow!