Polymorphism (Duck Typing) in Python

Use duck typing to write functions that work with any object having the required method.

IntermediateObject-Oriented ProgramsExample 25 of 25
polymorphism-duck-typing.py
1# Program to demonstrate polymorphism via duck typing
2
3class FileLogger:
4 def write(self, message):
5 print("[File]", message)
6
7class ConsoleLogger:
8 def write(self, message):
9 print("[Console]", message)
10
11def log_something(logger):
12 logger.write("Logging an event")
13
14log_something(FileLogger())
15log_something(ConsoleLogger())

Output

[File] Logging an event
[Console] Logging an event

What's going on

The function 'log_something' relies only on the presence of a 'write' method, not on concrete types.

After this program

If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.