Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Object-Oriented Programming  ›  Capstone Project

Polymorphism

Polymorphism 15 minPolymorphism lets one call work on many kinds of object, each answering in its own way, which replaces chains of type checks.

Polymorphism

Shelfwise's delivery estimate began as one line. Then e-books arrived, then gift cards, then audiobooks, and now delivery_days(item) is a ladder of isinstance checks that someone must extend, carefully, every time a new product appears. Polymorphism deletes the ladder.

The rule

One call, many shapes — let the object decide.

Polymorphism means the same call works on different kinds of object, and each one answers in its own way.

# Before: the caller decides by checking types
def delivery_days(item):
    if isinstance(item, EBook):
        return 0
    elif isinstance(item, GiftCard):
        return 1
    else:
        return 3

# After: each class answers for itself
class Product:
    def delivery_days(self):
        return 3

class EBook(Product):
    def delivery_days(self):
        return 0

class GiftCard(Product):
    def delivery_days(self):
        return 1

latest = max(item.delivery_days() for item in cart)

The caller writes item.delivery_days() once. At run time, the object's own class picks which version runs. Adding AudioBook means writing one new class; no existing function gets a new elif.

Polymorphism does not require inheritance. Python uses duck typing: if an object has a delivery_days() method, you can call it, whatever its class. Java and C# get the same effect through interfaces, where unrelated classes promise the same method.

You already use polymorphism every day. len() works on a list, a string and a dictionary, and each type supplies its own answer through a special method called __len__. len never checks what it was given; it just asks. Your Shelfwise classes can offer the same courtesy to the code that uses them.

This is also where the other pillars pay off. Encapsulation keeps each object's rules inside it, abstraction gives every product the same simple interface, inheritance can share defaults, and polymorphism lets one piece of code treat them all alike.

The shortcut

Whenever you see a type check that chooses behaviour — isinstance, type(x) ==, or a kind field in an if chain — move each branch into the class it describes, and replace the chain with one method call.

Removing the receipt-line ladderStep 1 of 4
  1. Spot the chain

    receipt_line(item) checks isinstance for Book, EBook and GiftCard to build different text.

The trap is a type check hiding under another name: if item.kind == "ebook" is the same ladder, and it grows the same way.

Drills

Answer fast — trust the rule.

quick drill

In for item in cart: total += item.shipping_cost(), who decides which shipping_cost runs?

quick drill

Which code smell does polymorphism most directly remove?

quick drill

A new product type, Magazine, is added. With polymorphism in place, what must change?

quick drill

In Python, two unrelated classes both define delivery_days(). Can one loop call it on both?

Remember

  • One call, many shapes: let the object decide.
  • Every type check that chooses behaviour is a method waiting to move into its class.
  • Trap: if item.kind == ... is the same ladder with a different name.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainRemove the type checks

Shelfwise's delivery_days(item) is an if isinstance(item, Book) ... elif isinstance(item, EBook) ... elif isinstance(item, GiftCard) chain, and it has to be edited every time a new product type is added. Explain how polymorphism removes the chain and what adding a new product type looks like afterwards.