Decide where an attribute belongs

Lesson 5 of 19 · Python Object Design

Some information belongs to each record, while other information is intended to be shared by the class. An attribute written in the class body belongs to the class; one assigned through self belongs to that instance.

class Marker:
    unit = "cm"

    def __init__(self, length):
        self.length = length

short = Marker(4)
long = Marker(9)
Marker.unit = "mm"
short.unit = "custom"
print(short.unit, long.unit, Marker.unit)

Output:

custom mm mm

For ordinary attributes, reading long.unit first checks the instance, then finds unit on Marker. Assigning short.unit creates an instance attribute that shadows the class attribute for short; it does not change Marker.unit. length is independently assigned for each instance. More advanced Python attribute mechanisms can alter lookup.

A mutable class attribute can surprise us:

class SharedTray:
    labels = []

a = SharedTray()
b = SharedTray()
a.labels.append("packed")
print(b.labels)

Output:

['packed']

Both lookups find the same class-level list. append changes that list; it does not create a new instance attribute. If each tray needs its own list, create self.labels = [] in __init__, as in the previous lesson. Class attributes can be useful for deliberately shared information, but changing one has wider effects. The marker example illustrates lookup, not a unit conversion: changing the label does not convert stored numbers.

Chapter contents