Comparison magic methods let you decide how objects compare to each other using operators like <, >, ==, and more.
0
0
Comparison magic methods in Python
Introduction
When you want to compare two custom objects to see if they are equal.
When sorting a list of your custom objects based on some property.
When checking if one object is greater or smaller than another.
When using comparison operators in conditions with your own classes.
Syntax
Python
def __eq__(self, other): # return True if self equals other def __lt__(self, other): # return True if self is less than other def __le__(self, other): # return True if self is less than or equal to other def __gt__(self, other): # return True if self is greater than other def __ge__(self, other): # return True if self is greater than or equal to other def __ne__(self, other): # return True if self is not equal to other
Each method should return a boolean (True or False).
Use these methods inside your class to customize how comparison operators work.
Examples
Checks if two objects have the same 'value' property.
Python
def __eq__(self, other): return self.value == other.value
Returns True if self's value is less than other's value.
Python
def __lt__(self, other): return self.value < other.value
Returns True if values are not equal.
Python
def __ne__(self, other): return self.value != other.value
Sample Program
This program creates a Box class with a volume. It compares boxes by their volume using ==, <, and > operators.
Python
class Box: def __init__(self, volume): self.volume = volume def __eq__(self, other): return self.volume == other.volume def __lt__(self, other): return self.volume < other.volume def __gt__(self, other): return self.volume > other.volume box1 = Box(10) box2 = Box(20) box3 = Box(10) print(box1 == box2) # False print(box1 == box3) # True print(box1 < box2) # True print(box2 > box3) # True
OutputSuccess
Important Notes
Only __eq__ and __ne__ are required for equality checks; others are for ordering.
If you define __eq__, also define __ne__ for consistent behavior.
Python can use functools.total_ordering to fill in missing comparison methods if you define __eq__ and one ordering method.
Summary
Comparison magic methods let you control how objects compare with ==, <, >, etc.
Define these methods inside your class to customize comparisons.
They return True or False based on your rules.