Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is Polymorphism?
What you need to know
Built-in polymorphism
You already use it daily. The same syntax does different things depending on the type:
print(len("upi"), len([1, 2]), len({"a": 1})) # 3 2 1print(1 + 2, "ab" + "cd", [1] + [2]) # 3 abcd [1, 2]len calls each object's __len__; + calls each object's __add__.
Duck typing
Functions like json.load(f) accept any object with a .read() method — a real file, an io.StringIO, or a network stream. No shared parent class is involved.
Overriding
A subclass can replace a parent method (see the inheritance question). Code that calls model.predict(x) runs whichever version belongs to the object's actual class.
Checking duck types statically: Protocol
Duck typing is flexible but gives no warning when an object lacks a method. typing.Protocol describes the required methods so mypy or pyright can check them, still without inheritance:
1from typing import Protocol23class Classifier(Protocol):4 def classify(self, text: str) -> str: ...Any class with a matching classify method satisfies Classifier for the type checker.
No overloading by signature
Python has no Java-style method overloading. If you define def f(self, x) and then def f(self, x, y), the second replaces the first. Use default arguments, or functools.singledispatch to choose an implementation by argument type.
A real-life example
An evaluation harness compares three ticket classifiers on the same test set: a keyword baseline, an LLM, and a fake used in CI. The harness only calls .classify():
1class KeywordBaseline:2 def classify(self, text):3 return "refund" if "refund" in text.lower() else "other"45class LLMClassifier:6 def __init__(self, model):7 self.model = model8 def classify(self, text):9 return "refund" if "money back" in text.lower() or "refund" in text.lower() else "other" # stands in for an API call1011class FakeClassifier:12 def classify(self, text):13 return "other"1415tests = [("I want my money back", "refund"), ("Refund pending", "refund"), ("Update address", "other")]16for clf in [KeywordBaseline(), LLMClassifier("chat-small"), FakeClassifier()]:17 score = sum(clf.classify(t) == y for t, y in tests)18 print(f"{type(clf).__name__:<16} {score}/{len(tests)}")19# KeywordBaseline 2/320# LLMClassifier 3/321# FakeClassifier 1/3The three classes share no parent. Adding a fine-tuned model next quarter means writing one more class with a classify method; the harness, the reports and the CI job do not change.
Follow-up questions to expect
- "Does Python support method overloading?" — Not by signature. A later definition replaces an earlier one; use defaults or
functools.singledispatch. - "What is duck typing?" — Using an object based on the methods it has, not its class.
- "How is polymorphism different from inheritance?" — Inheritance is one way to get polymorphism. In Python, duck typing gives polymorphism without any inheritance.