Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Implement Multiple Comparison Magic Methods for a Class

Implement comparison dunder methods to make objects comparable using <, <=, ==, !=, >=, >.

Python practice28 minMagic Methods & Operator OverloadingAdvancedLast updated April 11, 2026

Problem statement

Design a Box class that wraps a numeric size attribute. Implement the comparison magic methods so Box instances can be compared to each other using standard comparison operators. The comparison semantics: - Boxes are ordered by their size attribute. - Two boxes are equal if their sizes are equal. Implement these magic methods on Box: __eq__, __lt__, __le__, __gt__, and __ge__. If the other operand is not a Box, return NotImplemented so Python can handle reflected or type-mismatched comparisons.

Task

Practice implementing __eq__, __lt__, __le__, __gt__, and __ge__ so instances compare by a chosen attribute and behave consistently across all comparison operators.

Examples

Compare two boxes

Input

compare_demo(2, 3)

Output

(True, True, False, True, False, False)

Box(2) < Box(3) is True, <= is True, == is False, != is True, >= is False, > is False.

Input format

The tests will call compare_demo(a, b) where a and b are numeric sizes used to construct Box(a) and Box(b).

Output format

Return a 6-tuple: (a < b, a <= b, a == b, a != b, a >= b, a > b). Each element is a boolean.

Constraints

- Implement __eq__, __lt__, __le__, __gt__, and __ge__ directly on the Box class. - Comparisons should only work with other Box instances; return NotImplemented for other types.

Samples

Sample 1

Input

compare_demo(3, 3)

Output

(False, True, True, False, True, False)

Boxes with equal sizes: < is False, <= True, == True, != False, >= True, > False.