Velamuvi AIAcademy

Lesson 11 of 15 · Relationships

Polymorphism

Understand polymorphism in Python: one piece of code that works with many kinds of objects, shared method names, duck typing, and the fit and predict pattern used in machine learning.

  • 9 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • What polymorphism means in plain English
  • How shared method names let one loop handle many classes
  • What an interface is
  • What duck typing is and why Python uses it
  • How machine learning libraries rely on polymorphism

One action, many forms

Think of the word "open". You can open a door, a book, a bank account or an app. The word is the same, but each thing does it in its own way. You do not need a different word for each.

In code, polymorphism means you can write one piece of code that works with many different classes, as long as they all have the method it uses.

Polymorphism in action

Try it yourselfPython
class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14159 * self.radius ** 2


class Square:
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side * self.side


class Triangle:
    def __init__(self, base, height):
        self.base = base
        self.height = height

    def area(self):
        return 0.5 * self.base * self.height


shapes = [Circle(1), Square(4), Triangle(6, 3)]

total = 0
for shape in shapes:
    print(type(shape).__name__, round(shape.area(), 2))
    total += shape.area()

print("Total area:", round(total, 2))

The loop never asks "is this a circle or a square?". It just calls shape.area(), and each object knows how to work out its own area. To support a new shape, you write a new class with an area() method. The loop does not change at all.

Compare that with the alternative, a growing chain of checks that you would have to edit for every new shape:

if shape_type == "circle":
    area = 3.14159 * radius ** 2
elif shape_type == "square":
    area = side * side
elif shape_type == "triangle":
    ...

Interfaces: the shared method names

The interface is the agreement that makes polymorphism work. The loop above relies on one promise: "every shape has area()".

Polymorphism with inheritance

Often the classes share a parent, and each child overrides the same method:

Try it yourselfPython
class Payment:
    def __init__(self, amount):
        self.amount = amount

    def pay(self):
        return f"Paid {self.amount}"


class CardPayment(Payment):
    def pay(self):
        return f"Charged {self.amount} to the card"


class UpiPayment(Payment):
    def pay(self):
        return f"Sent {self.amount} by UPI"


class CashPayment(Payment):
    pass


def checkout(payments):
    for payment in payments:
        print(payment.pay())


checkout([CardPayment(1200), UpiPayment(350), CashPayment(80)])

checkout() works with every kind of payment, including ones that do not exist yet. CashPayment did not override pay(), so it uses the parent's version.

Duck typing

The classes do not need a shared parent. Here, a dog, a robot and a radio have nothing in common except a speak() method:

Try it yourselfPython
class Dog:
    def speak(self):
        return "Woof!"


class Robot:
    def speak(self):
        return "Beep boop."


class Radio:
    def speak(self):
        return "Now playing the morning news."


def make_it_talk(thing):
    print(thing.speak())


for thing in [Dog(), Robot(), Radio()]:
    make_it_talk(thing)

make_it_talk() does not check the type. It just calls speak(). Many languages require a formal shared parent for this. Python only requires that the method exists.

You have used polymorphism already

Python's built-in functions are polymorphic too. The same len(), + and for work on many types, because each type supplies its own magic methods:

Try it yourselfPython
print(len("hello"), len([1, 2, 3]), len({"a": 1}))
print(2 + 3, "Velamuvi" + " AI", [1] + [2])

for item in ("tuple", "items"):
    print(item)

When you added __len__ and __add__ to your own classes in the Magic Methods lesson, you were joining in with this.

The machine learning connection

Polymorphism is the reason you can swap one machine learning model for another by changing a single line. Every scikit-learn model shares the same interface: fit() to learn and predict() to guess. Here is a tiny version of that idea, with two very simple "models":

Try it yourselfPython
class AverageModel:
    """Always predicts the average of the training answers."""

    def fit(self, answers):
        self.guess = sum(answers) / len(answers)
        return self

    def predict(self):
        return self.guess


class LastValueModel:
    """Always predicts the most recent training answer."""

    def fit(self, answers):
        self.guess = answers[-1]
        return self

    def predict(self):
        return self.guess


sales = [120, 135, 128, 150, 162]

for model in [AverageModel(), LastValueModel()]:
    model.fit(sales)
    print(type(model).__name__, "predicts", model.predict())

The loop that trains and tests the models does not care which model it has. Real libraries work exactly like this, which is how you can try ten different models with the same few lines of code.

Common mistakes

Practice exercise

Write three different staff classes that share one interface, so one loop can run the whole payroll.

Your solutionPython
# Write three classes. Each has __init__ storing a name and its pay details,
# and a pay(self) method that returns the monthly pay:
# - FullTime(name, monthly)          pay = monthly
# - Hourly(name, rate, hours)        pay = rate * hours
# - Intern(name, stipend)            pay = stipend


staff = [FullTime("Ada", 60000), Hourly("Alan", 500, 40), Intern("Grace", 15000)]

total = 0
for person in staff:
    print(person.name, person.pay())
    total += person.pay()
print("Total:", total)

# Output must be exactly:
# Ada 60000
# Alan 20000
# Grace 15000
# Total: 95000
Knowledge check

What does duck typing mean in Python?

Summary

  • Polymorphism means different objects respond to the same method call in their own way.
  • An interface is the set of method names a group of classes share.
  • One loop or function can then work with every class that follows the interface, including future ones.
  • Duck typing: Python only needs the method to exist, not a shared parent.
  • Machine learning libraries rely on this: every model has fit() and predict().

Next: building objects out of other objects, and when that is better than inheritance.

Finished reading? Tick it off to track your progress.