Wren reweighs sample S01 on the crew's little scale. "It reads 40 grams today, not 42," he says. "Some dust must have come off."
Comet has two objects for S01 in her notebook, one for the field and one for the catalog. "If I change one," she asks, "does the other change too?"
Wren taps his clipboard. "What does the evidence say? Let's not guess. Let's run it."
Nova projects two identical boxes side by side. "How can I help?" she asks. "They look the same. Watch what happens when one of them changes."
Comet nods. "Lead programmer, predict first."
Instance variables hold data that belongs to one object. a.grams and b.grams are separate values, even when they start out the same.
This program uses the sample.py you wrote yesterday. The samples are made-up data from the FieldSim story.
# own_state.py
from sample import Sample
a = Sample("S01", "basalt", 42, 0, 2)
b = Sample("S01", "basalt", 42, 0, 2)
a.grams = 40
print(a.describe())
print(b.describe()) S01 basalt 40 g at (0, 2) S01 basalt 42 g at (0, 2)
Each object has its own state: its attributes and their values at a given time. After a.grams = 40, the two objects no longer have the same state.
Last week a misspelled key gave a KeyError. What does a misspelled attribute give?
# typo.py
from sample import Sample
s = Sample("S02", "quartz", 18, 2, 4)
print(s.label)
print(s.gram) S02
Traceback (most recent call last):
File "typo.py", line 6, in <module>
print(s.gram)
^^^^^^
AttributeError: 'Sample' object has no attribute 'gram'. Did you mean: 'grams'? AttributeError means an attribute does not exist on that object. The run shows Python even suggests the name you probably meant.
Reading a misspelled attribute stops the program. Watch what happens when Comet sets one instead.
# quiet_typo.py
from sample import Sample
s = Sample("S02", "quartz", 18, 2, 4)
s.gram = 20
print(s.describe())
print(s.gram) | Statement | True or false? |
|---|---|
| Two objects made with the same values are still separate objects. | ? |
| Changing a.grams also changes b.grams. | ? |
| Reading s.gram, which does not exist, stops with an AttributeError. | ? |
| Setting s.gram = 20 changes s.grams. | ? |
Each object keeps its own state, and typos leave clues. Tomorrow is Trace Friday: dict or class?