Menu
CoddyTech

Polymorphism and Duck Typing

Lesson 40 of 48 in Coddy's Python for JavaScript Developers course.

Write a caller against a useful behavior rather than a list of concrete class names. Polymorphism lets different objects respond to the same operation; duck typing focuses on whether they support the required operation at runtime.

JavaScript

class TextSize {
  measure(text) { return text.length; }
}
class FixedSize {
  measure(text) { return 7; }
}
for (const tool of [new TextSize(), new FixedSize()]) {
  console.log(tool.measure("cat"));
}

Python

class TextSize:
    def measure(self, text):
        return len(text)
class FixedSize:
    def measure(self, text):
        return 7
for tool in [TextSize(), FixedSize()]:
    print(tool.measure("cat"))

What changes

Both complete examples print 3 followed by 7 for this ASCII input. The classes have no custom shared base, but both provide measure(text) with compatible results. The caller needs that contract, not a particular ancestry. An object missing the method will fail when called; duck typing does not silently supply missing behavior. Method names alone are insufficient if argument requirements or return meanings differ. Document what callers can pass and what they receive.

Common mistake

A chain of type checks often defeats this flexibility. A new class with the right method should work without modifying the caller. Do not hard-code the expected outputs of known classes, either: the driver may supply new collaborators, repeat one, reorder them, or supply none. Delegation must use the current argument for every call.

Your task

Apply a common rendering interface to a variable list of objects. A locked probe records calls so the test checks collaboration as well as final text.

challenge icon

Challenge

Beginner

Implement Plain.render(text) returning text unchanged, Bracketed.render(text) returning text between [ and ], and render_all(renderers, text) returning a list of results in order. Both classes have no required constructor arguments. Input has a text line, a space-separated renderer-name line (possibly empty), and a prefix line. Renderer names are plain, bracket, exclaim, or probe. The locked driver supplies the last two classes; exclaim adds !, while probe adds the prefix. It prints one line per result, then calls:N for the probe call count. Each listed renderer must be called exactly once with the original text, including repeated names. The driver checks the probe's received arguments. Empty renderer lists return no results and print only calls:0. Do not inspect class names or require a shared base class. Submit the required class and function definitions only; input and printing belong to the locked driver.

Your code goes in the editable files plain.py and bracketed.py and functions.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable modules.

Try it yourself

from plain import Plain
from bracketed import Bracketed
from functions import render_all

class Exclaim:
    def render(self, text):
        return text + "!"

class Probe:
    def __init__(self, prefix):
        self.prefix = prefix
        self.calls = []

    def render(self, text):
        self.calls.append(text)
        return self.prefix + text

text = input()
names = input().split()
probe = Probe(input())
objects = {"plain": Plain(), "bracket": Bracketed(), "exclaim": Exclaim(), "probe": probe}
result = render_all([objects[name] for name in names], text)
for value in result:
    print(value)
assert probe.calls == [text] * names.count("probe"), "Call each probe once with the original text"
print(f"calls:{len(probe.calls)}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for JavaScript Developers

Practice on your own: Online Python compiler