Polymorphism (Duck Typing)
Use duck typing to write functions that work with any object having the required method.
IntermediateTopic: Object-Oriented Programs
Python Polymorphism (Duck Typing) Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to demonstrate polymorphism via duck typing
class FileLogger:
def write(self, message):
print("[File]", message)
class ConsoleLogger:
def write(self, message):
print("[Console]", message)
def log_something(logger):
logger.write("Logging an event")
log_something(FileLogger())
log_something(ConsoleLogger())Output
[File] Logging an event [Console] Logging an event
Understanding Polymorphism (Duck Typing)
The function 'log_something' relies only on the presence of a 'write' method, not on concrete types.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.