9/13
Part 3 of 4 · A class, one method at a timeLearn and do

A class keeps state between calls

Some coding rounds don't ask for one function. They ask for a small system: a store, a cache, a queue, whose methods are called one after another and share the same data. That's a class. The coding builds later in the plan are made of them, and they start the same way every time: __init__ makes the data, and every method reads or changes it through self.

class Tally:
    def __init__(self):
        self.total = 0

    def add(self, n):
        self.total += n
        return self.total


t = Tally()
t.add(2)
print(t.add(3), Tally().total)
5 0

self.total lives on the object, so the second add sees what the first one did. A new Tally() starts again at 0, because __init__ runs for each new object. Write a class like this one method at a time, and run the checks after each.

In the editor, write the three methods of Shelf, one line each.