0Pricing
Python Academy · Lesson

Polymorphism and Duck Typing

Write polymorphic code that works with any compatible object.

Polymorphism and Duck Typing is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Introduction

Polymorphism lets different objects respond to the same interface. Duck typing means: if it behaves like a duck, it is a duck.

What is Polymorphism?

Polymorphism means 'many forms'. The same method name works differently on different objects. Python embraces this heavily.
class Cat:
    def speak(self): return 'Meow'
class Dog:
    def speak(self): return 'Woof'
for animal in [Cat(), Dog()]:
    print(animal.speak())

Duck Typing

Python doesn't require a class hierarchy for polymorphism. If an object has the right method, it works. No need for interfaces.
class Duck:
    def quack(self): return 'Quack'
class Person:
    def quack(self): return 'I am quacking like a duck'
def make_it_quack(duck):
    print(duck.quack())
make_it_quack(Duck())
make_it_quack(Person())

Polymorphic Functions

len() works on strings, lists, dicts, tuples — all because they implement __len__. This is built-in polymorphism.
for obj in ['hello', [1,2,3], {'a':1}]:
    print(type(obj).__name__, len(obj))

Operator Overloading

+ works on ints, floats, strings, and lists because each implements __add__ differently.
print(1 + 2)        # int addition
print('a' + 'b')    # string concat
print([1] + [2])    # list concat

Protocol-Based Duck Typing

The iteration protocol: any object with __iter__ and __next__ works in for loops — no base class needed.
class Squares:
    def __init__(self, n): self.n,self.i=n,0
    def __iter__(self): return self
    def __next__(self):
        if self.i>=self.n: raise StopIteration
        x=self.i**2; self.i+=1; return x
print(list(Squares(5)))

EAFP vs LBYL

EAFP (Easier to Ask Forgiveness than Permission) uses try/except. LBYL (Look Before You Leap) uses if/hasattr. Python favors EAFP.
# LBYL:
if hasattr(obj, 'quack'):
    obj.quack()
# EAFP (Pythonic):
try:
    'hello'.quack()
except AttributeError:
    print('no quack')

isinstance() for Safe Dispatch

When you need type-specific behavior, isinstance() is cleaner than catching AttributeError.
def process(data):
    if isinstance(data, str):
        return data.upper()
    elif isinstance(data, list):
        return [x*2 for x in data]
print(process('hi'))
print(process([1,2,3]))

Abstract Base Classes as Protocols

from abc import ABC, abstractmethod defines formal protocols. Subclasses must implement abstract methods.
from abc import ABC, abstractmethod
class Drawable(ABC):
    @abstractmethod
    def draw(self): pass
class Circle(Drawable):
    def draw(self): print('O')
Circle().draw()

typing.Protocol (3.8+)

class MyProtocol(Protocol): defines structural subtyping without ABC. Works with mypy for static checks.
from typing import Protocol
class Quackable(Protocol):
    def quack(self) -> str: ...
def make_quack(x: Quackable) -> str:
    return x.quack()
print('protocol demo')

Polymorphism in Practice

Design APIs that accept any object with the right interface. This makes your code extensible without modification.
class JSONSerializer:
    def serialize(self, obj): import json; return json.dumps(obj)
class XMLSerializer:
    def serialize(self, obj): return f'<data>{obj}</data>'
def export(data, serializer):
    return serializer.serialize(data)
print(export({'x': 1}, JSONSerializer()))

Quick Check

What does duck typing mean in Python?

Recap

Polymorphism: same interface, different behavior. Duck typing: behavior matters, not type. Protocols define interfaces informally. EAFP (try/except) is Pythonic.

Keep Going

Excellent progress! Keep going to master the next concept.

Frequently asked questions

Is the “Polymorphism and Duck Typing” lesson free?

Yes — the full text of “Polymorphism and Duck Typing” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Polymorphism and Duck Typing”?

Write polymorphic code that works with any compatible object. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Polymorphism and Duck Typing” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Single Inheritance
  2. Method Overriding and super()
  3. Multiple Inheritance and MRO
  4. Polymorphism and Duck Typing
← Back to Python Academy