Python Polymorphism
Python · Functions & OOP
Theory
Polymorphism means 'many forms': the same method call can behave differently depending on the object that receives it. If Dog and Cat both define make_sound(), a loop can call animal.make_sound() on each one without checking its type - the dog prints Woof and the cat prints Meow.
Python relies on duck typing: if an object has the method you call, it works, whether or not the classes share a parent ('if it quacks like a duck...'). Polymorphism also appears through inheritance, where subclasses override a parent method, and in built-ins: len() works on strings, lists and dicts, and + adds numbers but joins strings, because each type implements the operation in its own way.
Why we use it
It lets you write general code that works with many types at once. New classes can be added later without changing the code that uses them, as long as they provide the same method names.
When to use it
Use it whenever several types share a common action (pay, export, make_sound) and the caller should not care which type it has. If you find long if/elif chains checking type(), polymorphism is usually the cleaner fix.
How it works
- for animal in [Dog(), Cat()]
- Take the next object
- Call animal.make_sound()
- Is the object a Dog? Yes: Run Dog.make_sound -> Woof. No: Run Cat.make_sound -> Meow.
- More animals? Yes: Go to the next object. No: Finish the loop.
- Output: Woof, Meow
Syntax
def speak(animal):
animal.make_sound()Example
class Dog:
def make_sound(self): print('Woof')
class Cat:
def make_sound(self): print('Meow')Key points
- Same method name behaves differently per class
- Enables flexible, extensible code
- Duck typing: shared method names matter, not a shared parent
- Built-ins like len() and + are polymorphic too
- Replaces long if type(x) == ... chains