Skip to content
BENIBIX Learn

Polymorphism

Development🧭 Programming ParadigmsObject-Oriented Programming

Also known as Method Overriding, Duck Typing

One name that works on many kinds of thing, each doing it its own way.

Think of it like

Think of it like saying speak to a dog and a cat. Each one answers in its own voice.

Example

Lucy's app keeps a list of shapes. One loop calls area() on each, and circles and squares each give the right answer.

Why it matters

It lets you add a new kind of thing without changing the code that uses it.

Definition

Polymorphism means one name can work on many kinds of thing. Each kind does it its own way. You call area() on a circle and on a square, and each works out its own area. The code that calls it does not need to know which shape it has. Python's len works on text, lists and more for the same reason. It lets one loop handle a mix of objects.

Example code

python
>>> len("hi"), len([1, 2, 3])
(2, 3)
The same len works on text and on a list.

Common mistake

Writing a long if chain that checks each type by hand. Let each class answer in its own way instead.

Key takeaways

  1. 1
    One name. Many kinds of thing.
  2. 2
    Each its own way. The object decides.
  3. 3
    Caller stays simple. No type checks needed.

Compare