Lesson 79 +10 XP

Polymorphism

Polymorphism

Polymorphism means "many forms". Different classes can have methods with the same name, and the right one runs based on the object.

Same name, different behavior

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def move(self):
        print("Drive!")

class Boat:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def move(self):
        print("Sail!")

class Plane:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def move(self):
        print("Fly!")

One loop, many behaviors

car = Car("Ford", "Mustang")
boat = Boat("Ibiza", "Touring 20")
plane = Plane("Boeing", "747")

for x in (car, boat, plane):
    x.move()
# Drive!
# Sail!
# Fly!

Each object runs its own version of move().

Polymorphism with inheritance

A child overriding a parent method is also polymorphism: the same call does different things.

Built-in polymorphism

Even len() is polymorphic: it works on strings, lists, tuples, and dicts.

TL;DR

  • Polymorphism = same method name, different implementations.
  • The object's own class decides which version runs.
  • A loop over different objects calls each one's method.
  • Inheritance overrides are one form of it.