Lesson guide
What this Python exercise practices
Compare Objects Using __eq__ is a beginner practice lesson that focuses on python practice, coding exercises, test feedback. It is designed to be solved in about 8 minutes with examples, starter code, and test feedback.
Prerequisites
- Python basics
- Variables
- Reading simple prompts
Difficulty and time
- Level
- Beginner
- Estimated time
- 8 minutes
Related public exercises
Summary
Learn to define equality between instances by implementing the __eq__ magic method.
Problem statement
Create a class Box that represents a rectangular box with width, height, and depth. Implement the __eq__ method so that two Box instances are considered equal (using ==) when their volumes (width * height * depth) are equal. If compared to a non-Box object, equality should be False.
Task
Implement the __eq__ method for a Box class so two Box instances compare equal when their volumes are equal.
Examples
Same volume
Input
Box(2, 3, 4) == Box(1, 6, 4)
Output
True
Explanation
First box volume = 2*3*4 = 24, second = 1*6*4 = 24, so they are equal.
Input format
The tests call the equality operator between Box instances or between a Box and another value, e.g. Box(2,3,4) == Box(1,6,4).
Output format
A boolean value: True if volumes are equal and other is a Box, otherwise False.
Constraints
- Width, height and depth are non-negative numbers (int or float). - When comparing to non-Box values, return False.
Samples
Sample input 0
Box(2,2,2) == Box(2,2,3)
Sample output 0
False
Explanation 0
Volumes 8 and 12 are not equal.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.