Comet lays last week's dict prototype beside this week's sample.py. "Both print the same four lines," she says. "So was the class worth it?"
Wren draws two columns on his graph paper. "What does the evidence say?" he asks. "Let's list what each one stopped from going wrong, and what each one kept together."
Nova highlights describe() in both files. "How can I help?" she asks. "Notice where describe() lives in each one."
Comet taps the class version. "Lead programmer, trace these first. Then we judge."
Trace each program on paper first, using the sample.py from Wednesday. The samples are made-up data from the FieldSim story.
# trace_objects.py
from sample import Sample
s = Sample("S03", "clay", 65, 3, 0)
t = Sample("S04", "mica", 7, 4, 5)
s.grams = s.grams - 15
t.grams = t.grams + s.grams
print(s.grams, t.grams)
print(s.is_heavy(), t.is_heavy()) | Step | s.grams | t.grams |
|---|---|---|
| after the two Sample lines | 65 | 7 |
| after s.grams = s.grams - 15 | 50 | 7 |
| after t.grams = t.grams + s.grams | 50 | 57 |
50 57 True True
# heavy_list.py
from sample import Sample
samples = [
Sample("S01", "basalt", 42, 0, 2),
Sample("S02", "quartz", 18, 2, 4),
Sample("S03", "clay", 65, 3, 0),
Sample("S04", "mica", 7, 4, 5),
]
heavy = []
light_total = 0
for s in samples:
if s.is_heavy():
heavy.append(s.label)
else:
light_total += s.grams
print(heavy)
print(light_total) A class bundles data and the functions that work on it. The method describe() now lives inside Sample, next to the data it reads.
Good programmers design each class first, its attributes and behaviors, in words or a diagram. The class then makes every object follow that design.
| Question | Dict prototype (week 1) | Sample class (week 2) |
|---|---|---|
| How is a sample made? | Type every key and value by hand | Call Sample(...) with the values |
| A key or value left out? | Found later, as a KeyError | Found at once, as a TypeError |
| How do you read the weight? | sample["grams"] | s.grams |
| Where is describe()? | A separate function | A method inside the class |
# test_sample.py
from sample import Sample
def test_describe():
s = Sample("S01", "basalt", 42, 0, 2)
assert s.describe() == "S01 basalt 42 g at (0, 2)"
def test_heavy():
assert Sample("S03", "clay", 65).is_heavy()
assert not Sample("S04", "mica", 7).is_heavy()
assert Sample("T1", "clay", 50).is_heavy()
test_describe()
test_heavy()
print("All Sample tests passed") | Statement | True or false? |
|---|---|
| describe() is a method inside the Sample class. | ? |
| A Sample made with too few arguments gives a KeyError later. | ? |
| is_heavy() gives True for a 50 g sample. | ? |
| A test of the edge value can catch a > that should be >=. | ? |
Dict or class? You can now say why. Tomorrow is Mission Quest: blueprint cards with your family.