bhylu.com

Advertisements

Code Challenge

Give a roster meaningful length and membership behaviour using the appropriate Python protocols.

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

Give a roster meaningful length and membership behaviour using the appropriate Python protocols.

Show the worked solution
Python

class Roster:
    def __init__(self, names):
        self.names = list(names)
    def __len__(self):
        return len(self.names)
    def __contains__(self, name):
        return name in self.names

roster = Roster(["Mira", "Dev"])
print(len(roster), "Dev" in roster)

Check the result

The results are 2 and True.

Test one more case

Test an empty roster and a missing name, then explain its truthiness.