When two objects take part

Lesson 10 of 19 · Python Object Design

One object can refer to another and ask it to perform an operation. Here a sign has a reference to a YearSpan. Rather than changing the span’s internal attributes, the sign delegates a revision to its method.

class YearSpan:
    def __init__(self, start, end):
        self.revise(start, end)

    def revise(self, start, end):
        if start > end:
            raise ValueError("start must not follow end")
        self._start = start
        self._end = end

    def bounds(self):
        return (self._start, self._end)

class Sign:
    def __init__(self, title, span):
        self.title = title
        self.span = span

    def correct_years(self, start, end):
        self.span.revise(start, end)

period = YearSpan(1910, 1920)
sign = Sign("Archive", period)
sign.correct_years(1912, 1922)
print(sign.title, period.bounds())
try:
    sign.correct_years(1930, 1920)
except ValueError as error:
    print(error)
print(sign.span is period, sign.span.bounds())

Output:

Archive (1912, 1922)
start must not follow end
True (1912, 1922)

The sign stores a reference to the same span as period, not a copy. The successful correction is therefore visible through both names. On the rejected correction, revise raises before changing its pair; the exception travels to the caller, and the previous years remain.

sign --> Sign --> span --+--> YearSpan: 1912, 1922
period ------------------+

Here __init__ calls self.revise to reuse the check. If a subclass overrides revise, that override can run during initialization before subclass attributes are ready; designs intended for inheritance should account for that risk.

Delegation keeps the ordering check with the object responsible for the years. It does not automatically make every multi-object operation atomic: if a method changes one object and a later step fails on another, the first change may remain. Real coordination may require rollback or a transaction supplied by the storage system. This in-memory example does neither, and assumes callers supply a YearSpan-like object.

Chapter contents