Name a kind of record

Lesson 3 of 19 · Python Object Design

Object-oriented programming (OOP) is a way to organize programs around objects that combine state and behavior. It can coexist with functions; it does not require every problem to become a class. A class defines a kind of object. An instance is one particular object of that class. Let’s represent each spool as an instance, so a label and a remaining length travel together.

class Spool:
    def __init__(self, label, remaining):
        self.label = label
        self.remaining = remaining

blue = Spool("blue", 12)
gold = Spool("gold", 7)
print(blue.label, blue.remaining)
print(gold.label, gold.remaining)

Output:

blue 12
gold 7

Spool("blue", 12) creates an instance. Python then calls __init__ to initialize it: self refers to that new instance, while label and remaining receive the supplied arguments. __init__ initializes; it is not itself the allocation step. The assignments create instance attributes, named values on that particular object. The dot in blue.label reads an attribute.

Spool class
   | creates                | creates
   v                        v
blue instance              gold instance
label: blue                label: gold
remaining: 12              remaining: 7

The two calls create separate objects, so assigning blue.remaining = 8 does not assign gold.remaining. They could still refer to the same mutable value if we explicitly supplied one; separate objects do not automatically imply separate contents. Ordinary Python classes also do not automatically enforce a fixed set of attributes. Here we have not yet added the cutting rule, so a caller can assign an invalid length. The next chapter gives that rule a supported home.

Chapter contents