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
What is Polymorphism?
class Cat:
def speak(self): return 'Meow'
class Dog:
def speak(self): return 'Woof'
for animal in [Cat(), Dog()]:
print(animal.speak())Duck Typing
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
for obj in ['hello', [1,2,3], {'a':1}]:
print(type(obj).__name__, len(obj))Operator Overloading
print(1 + 2) # int addition
print('a' + 'b') # string concat
print([1] + [2]) # list concatProtocol-Based Duck Typing
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
# LBYL:
if hasattr(obj, 'quack'):
obj.quack()
# EAFP (Pythonic):
try:
'hello'.quack()
except AttributeError:
print('no quack')isinstance() for Safe Dispatch
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
class Drawable(ABC):
@abstractmethod
def draw(self): pass
class Circle(Drawable):
def draw(self): print('O')
Circle().draw()typing.Protocol (3.8+)
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
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
Recap
Keep Going
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
- Single Inheritance
- Method Overriding and super()
- Multiple Inheritance and MRO
- Polymorphism and Duck Typing