
Bug hunt
The Shared Satchel
Attributes can live in two places:
class Explorer:
guild = "Lantern Guild" # class attribute: shared by all
def __init__(self, name):
self.name = name # instance attribute: one per object
A class attribute is stored once, on the class. Every instance can
read it (ada.guild), and you change it through the class
(Explorer.guild = ...). That's great for constants and counters.
Two classic traps:
- A mutable class attribute (like a list) is shared, so appending through one object changes it for everyone.
self.count += 1reads the class value but then creates a new instance attribute onself. The class attribute never changes! UseClassName.count += 1instead.
The bug
The quartermaster made satchels for Ada and Bo. Ada packed a rope, and
somehow it showed up in Bo's satchel too. And the counter of satchels
made still says 0.
Assignment
- Give every satchel its own
itemslist. - Make
Satchel.madecount how many satchels have been created.
- Give every satchel its own
itemslist. - Make
Satchel.madecount how many satchels have been created.
main.py Python sleeping
Press Run to try your code, then Check to test it.