Polymorphism (Duck Typing)

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

PythonIntermediate
Python
# 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

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