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

Friday

Trace Friday: Dict or class?
// A class is a blueprint, and each object keeps its own state
⏱ about 30 min

Friday: Trace Friday: Dict or Class?

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 object programs

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())
Steps.gramst.grams
after the two Sample lines657
after s.grams = s.grams - 15507
after t.grams = t.grams + s.grams5057
TRACE TRACE_OBJECTS.PY
  • Read the question.
  • Tap your answer.
What is the first line?
What is the second line?
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)
TRACE HEAVY_LIST.PY
  • Read the question.
  • Tap your answer.
What does print(heavy) show?
What does print(light_total) show?

Dict or class?

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.

QuestionDict prototype (week 1)Sample class (week 2)
How is a sample made?Type every key and value by handCall Sample(...) with the values
A key or value left out?Found later, as a KeyErrorFound at once, as a TypeError
How do you read the weight?sample["grams"]s.grams
Where is describe()?A separate functionA method inside the class

A test file for Sample

# 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")
READ THE TESTS
  • Read the question.
  • Tap your answer.
Why test a sample of exactly 50 g?
Someone changes is_heavy() to grams > 50. Which assert fails first?
At your computer
1. Type trace_objects.py and heavy_list.py, save them in fieldsim and check your traces.
2. Type test_sample.py and run it. Check for the one line it prints.
3. Change >= to > in is_heavy() and save sample.py. Run test_sample.py and read the message.
4. Change it back to >= and run the tests again.
  1. A class bundles data and methods, and calling it makes a new object.
  2. Python runs __init__ for each new object, with the object as self and your arguments after it.
  3. Each object keeps its own attribute values, reached with a dot.
  4. A missing argument gives a TypeError at once. A misspelled attribute gives an AttributeError when it is read.
  5. sample.py is the first real FieldSim file.
StatementTrue 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 >=.?
WHY THIS EXERCISEThe class keeps describe() with its data, too few arguments give a TypeError at once, and edge tests catch the wrong comparison.

Dict or class? You can now say why. Tomorrow is Mission Quest: blueprint cards with your family.

← Thursday