bhylu.com

Advertisements

Polymorphism

Different objects can support the same useful operation without sharing one concrete implementation. Python often relies on this through duck typing and protocols.

Understand the idea

A reporting function can call render on any object that honours that small interface. It does not need a chain of type tests for every implementation. Document the expected return type and failure behaviour so a new implementation can be substituted safely. Type annotations and Protocol can express such contracts for static checking.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Plain:
    def render(self):
        return "Ready"

class Emphasised:
    def render(self):
        return "READY"

for message in [Plain(), Emphasised()]:
    print(message.render())

Read the result

The outputs differ, but the calling loop uses the same render operation for both.

Try one change

Write a function that accepts either message and returns its render result without an isinstance branch.