Theory of Intelligence
PYTHON PROGRAMMING•Object Oriented Python•Four Pillars•2.3 Polymorphism

2.3.1 Polymorphism

Subtopics: Polymorphism and Duck Typing.

2.3.1 Polymorphism

Polymorphism (Python OOP)

Polymorphism means “many forms”.

In Python OOP, it usually means:

  • Different classes can have the same method name.
  • You can call that method without caring about the exact class.

This makes code flexible and easy to extend.


Real-Life Analogy

If you say “open”:

  • A door opens one way.
  • A file opens in another way.

Same word, different behavior.


Example 1: Same Method, Different Classes

PYTHON
class Dog:
    def speak(self):
        return "Woof"


class Cat:
    def speak(self):
        return "Meow"


def make_animal_speak(animal):
    # We don't check type. We just call speak().
    print(animal.speak())


make_animal_speak(Dog())
make_animal_speak(Cat())

This is polymorphism using Python’s style called duck typing:

  • “If it has a speak() method, treat it like an animal.”

Example 2: Polymorphism with Inheritance

PYTHON
class Shape:
    def area(self):
        raise NotImplementedError


class Rectangle(Shape):
    def __init__(self, w, h):
        self.w = w
        self.h = h

    def area(self):
        return self.w * self.h


class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return 3.14159 * self.r * self.r


shapes = [Rectangle(3, 4), Circle(2)]
for s in shapes:
    print(s.area())

Same method call: s.area().

Different results depending on object type.


Why Polymorphism Is Powerful

  • Easy to extend: add a new class (Triangle) and implement area().
  • Existing code that loops over shapes will continue to work.

Common Beginner Mistakes

  • Using too many if type(...) checks

    • Usually you don’t need them. Let polymorphism do the work.
  • Forgetting to implement the method in a child class

    • You’ll get errors (or wrong behavior). That’s a sign the interface is not followed.

Quick Practice

Create three classes:

  • EmailNotification with method send(message)
  • SMSNotification with method send(message)
  • PushNotification with method send(message)

Write a function notify_all(notifiers, message) that loops and calls send().

Discuss theoretical concepts, mathematical formulas, and architectural foundations.

Supports inline code with `backticks`
No comments yet. Be the first to start the discussion!