Bird
Raised Fist0
Pythonprogramming~10 mins

Comparison magic methods in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Comparison magic methods
Create object A
Create object B
Call __eq__?
YesCompare A and B for equality
Return True/False
Call __lt__?
YesCompare A < B
Return True/False
Call other comparison methods similarly
Use result in if/print/etc
End
Objects are created, then Python calls special methods like __eq__ or __lt__ to compare them, returning True or False.
Execution Sample
Python
class Box:
    def __init__(self, size):
        self.size = size
    def __eq__(self, other):
        return self.size == other.size

b1 = Box(5)
b2 = Box(5)
print(b1 == b2)
This code creates two Box objects and compares them using the __eq__ method to check if their sizes are equal.
Execution Table
StepActionEvaluationResult
1Create b1 with size=5b1.size = 5b1 object created
2Create b2 with size=5b2.size = 5b2 object created
3Compare b1 == b2Call b1.__eq__(b2)Return b1.size == b2.size
4Evaluate b1.size == b2.size5 == 5True
5Print resultprint(True)Output: True
💡 Comparison done, result True printed, program ends
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
b1.sizeN/A5555
b2.sizeN/AN/A555
comparison_resultN/AN/AN/ATrueTrue
Key Moments - 3 Insights
Why does b1 == b2 return True even though they are different objects?
Because the __eq__ method compares their sizes, not their memory addresses. See execution_table step 3 and 4 where __eq__ returns True based on size.
What happens if __eq__ is not defined?
Python would check if b1 and b2 are the exact same object (memory address), so b1 == b2 would be False. This is why defining __eq__ changes comparison behavior.
Can other comparison operators like < or > be customized similarly?
Yes, by defining __lt__, __gt__, __le__, __ge__ methods. Python calls these when using <, >, <=, >= respectively.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of b1 == b2 at step 4?
ATrue
BFalse
CError
DNone
💡 Hint
Check the 'Result' column at step 4 in execution_table.
At which step is the __eq__ method called?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column to find when __eq__ is invoked.
If b2.size was 6 instead of 5, what would be the output at step 5?
ATrue
BError
CFalse
DNone
💡 Hint
Compare sizes in execution_table step 4; different sizes mean __eq__ returns False.
Concept Snapshot
Comparison magic methods:
- __eq__(self, other): equality (==)
- __lt__(self, other): less than (<)
- __gt__(self, other): greater than (>)
- __le__, __ge__, __ne__ for other comparisons
Define these in classes to customize how objects compare.
Python calls these automatically during comparisons.
Full Transcript
This visual trace shows how Python uses comparison magic methods like __eq__ to compare objects. First, two Box objects are created with size 5. When comparing b1 == b2, Python calls b1.__eq__(b2), which compares their sizes. Since both sizes are 5, __eq__ returns True. This result is printed. If __eq__ was not defined, Python would compare object identities instead. Other comparison methods like __lt__ can be defined similarly to customize <, >, <=, >= behavior.

Practice

(1/5)
1. Which magic method in Python is used to define the behavior of the equality operator ==?
easy
A. __eq__
B. __lt__
C. __ne__
D. __gt__

Solution

  1. Step 1: Understand the equality operator

    The == operator checks if two objects are equal.
  2. Step 2: Identify the corresponding magic method

    In Python, __eq__ is the method that defines equality behavior.
  3. Final Answer:

    __eq__ -> Option A
  4. Quick Check:

    Equality operator uses __eq__ [OK]
Hint: Remember: eq means equal, so __eq__ handles == [OK]
Common Mistakes:
  • Confusing __eq__ with __lt__ or __gt__
  • Thinking __ne__ handles equality
  • Mixing up method names with comparison operators
2. Which of the following is the correct syntax to define the less than operator < in a Python class?
easy
A. def __lt__(self):
B. def __less_than__(self, other):
C. def __less__(self, other):
D. def __lt__(self, other):

Solution

  1. Step 1: Recall the magic method name for <

    The method for < is __lt__ and it takes two parameters: self and other.
  2. Step 2: Check method signature correctness

    Correct syntax is def __lt__(self, other):. Other options have wrong names or missing parameters.
  3. Final Answer:

    def __lt__(self, other): -> Option D
  4. Quick Check:

    Less than operator uses __lt__(self, other) [OK]
Hint: Magic methods for comparisons always take self and other [OK]
Common Mistakes:
  • Using wrong method names like __less_than__
  • Omitting the other parameter
  • Using incorrect method signatures
3. What will be the output of the following code?
class Number:
    def __init__(self, value):
        self.value = value
    def __gt__(self, other):
        return self.value > other.value

n1 = Number(5)
n2 = Number(3)
print(n1 > n2)
medium
A. False
B. TypeError
C. True
D. None

Solution

  1. Step 1: Understand the __gt__ method

    The __gt__ method compares self.value and other.value.
  2. Step 2: Evaluate the comparison

    n1.value is 5 and n2.value is 3, so 5 > 3 is True.
  3. Final Answer:

    True -> Option C
  4. Quick Check:

    5 > 3 = True [OK]
Hint: Check the values inside objects when comparing [OK]
Common Mistakes:
  • Forgetting to compare attributes inside objects
  • Expecting print to show object addresses
  • Confusing __gt__ with __lt__
4. Identify the error in the following class that tries to implement the not equal operator !=:
class Item:
    def __init__(self, val):
        self.val = val
    def __ne__(self):
        return self.val != other.val
medium
A. The class should inherit from object explicitly
B. __ne__ method is missing the other parameter
C. The __ne__ method should return True always
D. The __init__ method is missing self

Solution

  1. Step 1: Check __ne__ method signature

    The __ne__ method must take two parameters: self and other.
  2. Step 2: Identify missing parameter

    Here, other is used but not declared as a parameter, causing an error.
  3. Final Answer:

    __ne__ method is missing the other parameter -> Option B
  4. Quick Check:

    __ne__ needs (self, other) parameters [OK]
Hint: Comparison methods always take self and other [OK]
Common Mistakes:
  • Omitting the other parameter in comparison methods
  • Misunderstanding method signatures
  • Thinking inheritance from object is required in Python 3
5. You want to create a class Box where two boxes are considered equal if their volumes are equal. Which magic method should you implement and how?
class Box:
    def __init__(self, length, width, height):
        self.length = length
        self.width = width
        self.height = height
    # Your code here
hard
A. Implement __eq__(self, other) to compare volumes: return self.length * self.width * self.height == other.length * other.width * other.height
B. Implement __lt__(self, other) to compare volumes
C. Implement __ne__(self, other) to compare volumes
D. Implement __gt__(self, other) to compare volumes

Solution

  1. Step 1: Identify the comparison needed

    Equality means using ==, so implement __eq__.
  2. Step 2: Define volume comparison inside __eq__

    Calculate volume for both boxes and compare for equality.
  3. Final Answer:

    Implement __eq__(self, other) to compare volumes: return self.length * self.width * self.height == other.length * other.width * other.height -> Option A
  4. Quick Check:

    Equality uses __eq__ comparing volumes [OK]
Hint: Use __eq__ to define equality based on volume [OK]
Common Mistakes:
  • Using __lt__ or __gt__ for equality
  • Not comparing volumes but attributes directly
  • Forgetting to implement __eq__ for == operator