Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Implement __str__ for a Point ClassE02. Define __repr__ for a Person ObjectE03. Compare Objects Using __eq__E

Problem No 3

Compare Objects Using __eq__

Easy

8 minute session

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.

Code editor
Loading editor…

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.

09:18 AM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.