Make Tasks Sortable by Priority
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 Task class with name and priority (an integer, lower = more urgent). Add __lt__ to compare by priority and __repr__ to return 'Task(<name>, priority=<priority>)'. Create three tasks: Task('Email', 3), Task('Bug fix', 1), Task('Meeting', 2). Sort them and print each one.
# Create the Task class with __lt__ and __repr__
More Magic Methods exercises
- Add String Representations to a BookBeginner
- Build a Team with __len__Beginner
- Fix the Broken Equality CheckIntermediate
- Make a Gradebook IndexableIntermediate
- Predict the Magic Method OutputIntermediate
- Create a Callable FormatterAdvanced
- Refactor a Playlist with Magic MethodsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz