← Back to course
Python 11-12 / Week 02 / Monday
1/6
Week 02 · Classes and Objects

Monday

A blueprint for samples
// A class is a blueprint, and each object keeps its own state
⏱ about 30 min

Monday: A Blueprint for Samples

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 is a blueprint

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.

A first Sample class

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__.

PREDICT FIRST_CLASS.PY
  • Read the question.
  • Tap your answer.
What does print(a.label, a.kind) show?
What does print(a.grams + b.grams) show?
How many Sample objects does the program make?
S01 basalt
18
60

Every argument goes to __init__

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'
READ THE TYPEERROR
  • Read the question.
  • Tap your answer.
Which parameter does the message say is missing?
Did print(c.label) run?

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.

At your computer
1. Type first_class.py, save it in your fieldsim folder and run it.
2. Make a third object, c = Sample("S03", "clay", 65). Print c.kind and c.grams.
3. Change the last line to print(a.grams + b.grams + c.grams). Predict, then run it.
4. Remove 65 from your c line and run it. Read the TypeError, then put 65 back.
StatementTrue 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.?
WHY THIS EXERCISECalling Sample(...) makes a new object and Python runs __init__ for it, passing the arguments along.
In a = Sample("S01", "basalt", 42), what is a.kind?
Which method does Python run for every new Sample object?

One blueprint, many samples. Tomorrow you will slow down a constructor call and see what self really is.