logo
45

Polymorphism

⏱️ 25 min

Polymorphism: One Interface, Multiple Implementations

What might confuse you right now

"What's the point of same-name methods with different implementations?"

The point is that the caller only cares about a consistent interface -- no need for type-checking branches.

One-line definition

Polymorphism is different objects providing their own implementation for the same interface.

Real-life analogy

"Pay" works for credit cards, PayPal, and cash. The caller just calls pay().

Minimal runnable example

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

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

for animal in [Cat(), Dog()]:
    print(animal.speak())

Quick quiz (5 min)

  1. Write two classes that implement pay().
  2. Use a single loop to call different payment objects.
  3. Add a third payment method without changing the caller.

Quiz answer guidelines & grading criteria

  • Answer direction: working code that covers core conditions and edge inputs from the prompt.
  • Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): Clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.

Transfer task (homework)

Implement an "exporter" interface: CSVExporter, JSONExporter, MarkdownExporter.

Acceptance criteria

You can independently:

  • Design a unified method signature
  • Add new implementations without modifying the main calling flow
  • Explain how polymorphism improves extensibility

Common errors & debugging steps (beginner edition)

  • Can't understand the error: read the last line for the error type (e.g., TypeError, NameError), then trace back to the relevant code line.
  • Not sure about a variable's value: temporarily add print(variable, type(variable)) at key points to verify data matches expectations.
  • Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.

Common misconceptions

  • Misconception: Polymorphism requires a complex inheritance tree.
  • Reality: Python commonly uses duck typing to achieve polymorphism. No inheritance needed.