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
Run in browser1# Program to demonstrate polymorphism via duck typing23class FileLogger:4 def write(self, message):5 print("[File]", message)67class ConsoleLogger:8 def write(self, message):9 print("[Console]", message)1011def log_something(logger):12 logger.write("Logging an event")1314log_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.