Follow names and references

Lesson 4 of 19 · Python Object Design

A name is not a container holding a private copy of an object. Assignment can make another name refer to the same object. Let’s use a small class with a mutable list so that a change is visible.

class Tray:
    def __init__(self):
        self.labels = []

first = Tray()
second = Tray()
also_first = first
also_first.labels.append("ready")
print(first.labels)
print(second.labels)
print(also_first is first)

Output:

['ready']
[]
True

Each call creates a tray and a fresh list. also_first = first does not call Tray() and does not copy anything. Both names refer to the same tray, so appending through either reaches the same list. second has its own list.

first ------+--> tray A --> ["ready"]
also_first -+
second --------> tray B --> []

is asks whether two references identify the same object. Equality, written ==, asks whether values compare equal; distinct objects can compare equal. Reassigning a name changes what that name refers to, while mutating a list changes the existing list. The distinction matters again when we return or copy a collection in the next chapter.

Chapter contents