Comet holds up last week's printout with the KeyError circled in orange. "I want samples that cannot forget a key," she says. "Every sample should have the same parts, every time."
Wren lays four sample tokens on the table, one for each star on the field map. "What does the evidence say?" he asks. "All four have a label, a kind and a weight. Only the values differ."
Nova projects one outline, then stamps four copies from it. "How can I help?" she asks. "Python has a tool for this: a class. Write the outline once, then make each sample from it."
Comet sharpens her pencil. "Lead programmer, let's write the outline."
A class bundles data and the functions that work on it. Making a class makes a new type, so you can make new instances of it.
An object is one instance of a class. The class is the blueprint for the attributes and behaviors every object of that type has.
An object holds state, its attributes, and behavior, its methods. You reach an attribute with a dot, like a.label.
This first step has only a constructor, __init__, and three attributes. The four field samples are made-up data from the FieldSim story.
# first_class.py
class Sample:
"""One sample token from the test field."""
def __init__(self, label, kind, grams):
self.label = label
self.kind = kind
self.grams = grams
a = Sample("S01", "basalt", 42)
b = Sample("S02", "quartz", 18)
print(a.label, a.kind)
print(b.grams)
print(a.grams + b.grams) You make an object by calling the class like a function: Sample("S01", "basalt", 42).
Because the class has an __init__ method, Python runs it for the new object. The arguments you give are passed on to __init__.
S01 basalt 18 60
What if Comet leaves out the weight? The run below shows Python will not make the object.
# missing_grams.py
class Sample:
def __init__(self, label, kind, grams):
self.label = label
self.kind = kind
self.grams = grams
c = Sample("S03", "clay")
print(c.label) Traceback (most recent call last):
File "missing_grams.py", line 9, in <module>
c = Sample("S03", "clay")
TypeError: Sample.__init__() missing 1 required positional argument: 'grams' This is the fix for Comet's KeyError problem. A sample cannot be made without all three values, so no sample can be missing its weight.
| Statement | True or false? |
|---|---|
| One class can make many objects. | ? |
| You make an object by calling the class like a function. | ? |
| Python runs __init__ only if you call it by name yourself. | ? |
| An attribute is reached with a dot, like a.grams. | ? |
One blueprint, many samples. Tomorrow you will slow down a constructor call and see what self really is.