Change behavior carefully

Lesson 16 of 19 · Python Object Design

A subclass can override a method by defining the same name. It can replace the implementation or use super() to extend the inherited behavior. A base may have several subclasses; they are siblings, not subclasses of each other.

class Caption:
    def __init__(self, text):
        self.text = text

    def render(self):
        return self.text

class QuietCaption(Caption):
    pass

class MarkedCaption(Caption):
    def render(self):
        return "* " + super().render()

for caption in (QuietCaption("Open"), MarkedCaption("Open")):
    print(caption.render())

Output:

Open
* Open

pass means the class body adds nothing here, so QuietCaption inherits render. MarkedCaption.render calls the base implementation and adds a marker. Both accept a no-argument render() call and return a string; the formatting differs.

        Caption
       /       \
QuietCaption  MarkedCaption

A matching call shape does not by itself make an override safe. If the base promises a string, returning None would break callers. If it promises no mutation, an override that silently changes data breaks that expectation too. Deep chains are possible, but each layer adds another place to look for behavior and another set of promises to preserve; add levels for a clear purpose rather than to create a taxonomy.

Chapter contents