Build a Team with __len__
Beginner · Write the code · from Python Magic Methods: The Complete __dunder__ Guide
From the lesson: Python Magic Methods: The Complete __dunder__ Guide
Think of a TV remote control. You press the volume button, and the TV gets louder. You press the channel button, and it switches channels. You don't think about how it works - you just press the button and the TV responds.
Read the lessonCreate a Team class that stores a list of members (passed to __init__). Add __len__ to return the number of members. Create a team with ['Alice', 'Bob', 'Carol'] and print its length. Then create an empty team Team([]) and print whether it's truthy using bool().
# Create the Team class with __len__
More Magic Methods exercises
- Add String Representations to a BookBeginner
- Fix the Broken Equality CheckIntermediate
- Make a Gradebook IndexableIntermediate
- Predict the Magic Method OutputIntermediate
- Make Tasks Sortable by PriorityIntermediate
- Create a Callable FormatterAdvanced
- Refactor a Playlist with Magic MethodsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz