Editor

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 lesson

Create 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

All Python exercises · 50 practice problems · Object-Oriented Programming quiz