Use one operation for many objects

Lesson 14 of 19 · Python Object Design

Different objects can answer the same request in different ways. This is polymorphism: caller code uses a shared operation without selecting an implementation by class name.

class PlainLabel:
    def render(self, text):
        return text

class BracketLabel:
    def render(self, text):
        return "[" + text + "]"

def show_heading(style, title):
    print(style.render(title))

for style in (PlainLabel(), BracketLabel()):
    show_heading(style, "Schedule")

Output:

Schedule
[Schedule]

Both render methods accept one text argument and return a string, but their bodies differ. The caller invokes the method on the actual object; Python finds the matching implementation. Neither class inherits from the other.

show_heading(style, title) -> style.render(title)
                                |             |
                            plain text    bracketed text

This is duck typing: suitability depends on the behavior the caller uses, rather than a required common parent. If render is absent, the call raises AttributeError; incompatible arguments can raise TypeError. Even a method with the right name and arguments can break the contract by returning an unexpected value. A type annotation may document expectations, but Python does not enforce annotations by itself.

The interface must describe meaning as well as spelling. For example, if a caller expects a string, a method that prints a result and returns None does not satisfy that promise. Shared behavior can also arise through inheritance, which we examine in the next chapter.

Chapter contents