Make a Gradebook Indexable
Intermediate · 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 Gradebook class that stores a dictionary of grades (passed to __init__). Add __getitem__ so you can look up a student's grade with bracket notation. Add __contains__ so you can check if a student is in the gradebook with in. Create a gradebook with {'Alice': 95, 'Bob': 82}, print Alice's grade using brackets, and print whether 'Carol' is in the gradebook.
More Magic Methods exercises
- Add String Representations to a BookBeginner
- Build a Team with __len__Beginner
- Fix the Broken Equality CheckIntermediate
- 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