Browse OOP reference
Relationships and dispatch

What is polymorphism?

On this page

Polymorphism allows the same expression to work across multiple types. For example, a report writer can invoke sink.write(text) with a file or an in-memory buffer. Agreement on the method name is just the beginning. Both sinks must meet the writer’s expectations for encoding, errors and ordering.

Worked example

Python
from io import StringIO

def publish(sink):
    sink.write("release 4")

class Log:
    def __init__(self):
        self.entries = []
    def write(self, text):
        self.entries.append(text)

memory, log = StringIO(), Log()
for sink in (memory, log):
    publish(sink)
assert memory.getvalue() == log.entries[0]

Python tutorial on classes

Explore class relationships in the OOP Playground

What is duck typing?What is method overloading?What is nominal typing?

All OOP questions

Search ObjectFAQ