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
Pythonfrom 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]Explore class relationships in the OOP Playground