bhylu.com

Advertisements

Code Challenge

Write an instance method that increments its own counter and returns the new value. Use two calls to show retained state.

Understand the idea

Write your own solution before opening the worked answer. Predict the output from the supplied values, then compare the actual result. Check both an ordinary case and the boundary described below; a passing example is more useful when you can explain why it passes.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

Your task

Write an instance method that increments its own counter and returns the new value. Use two calls to show retained state.

Show the worked solution
Python

class Counter:
    def __init__(self):
        self.value = 0
    def step(self):
        self.value += 1
        return self.value

counter = Counter()
print(counter.step(), counter.step())

Check the result

The results are 1 and 2.

Test one more case

Create a second counter and confirm that it begins independently at zero.