How to implement Python __lt__ __gt__ custom (overloaded) operators?

Python provides magic methods to define custom behavior for comparison operators. The operators <, <=, >, >=, == and != can be overloaded using the __lt__, __le__, __gt__, __ge__, __eq__ and __ne__ magic methods respectively.

Basic Implementation

Let's create a Distance class that overloads the < and > operators to compare distances in feet and inches ?

class Distance:
    def __init__(self, feet=5, inches=5):
        self.feet = feet
        self.inches = inches

    def __str__(self):
        return f"{self.feet} feet {self.inches} inches"

    def __lt__(self, other):
        # Convert both distances to inches for comparison
        self_total = self.feet * 12 + self.inches
        other_total = other.feet * 12 + other.inches
        return self_total < other_total

    def __gt__(self, other):
        # Convert both distances to inches for comparison
        self_total = self.feet * 12 + self.inches
        other_total = other.feet * 12 + other.inches
        return self_total > other_total

    def __eq__(self, other):
        return self.feet == other.feet and self.inches == other.inches

# Creating distance objects
d1 = Distance(5, 5)  # 65 inches
d2 = Distance(6, 2)  # 74 inches
d3 = Distance(4, 8)  # 56 inches

print(f"d1: {d1}")
print(f"d2: {d2}")
print(f"d3: {d3}")
print()
print(f"d1 < d2: {d1 < d2}")
print(f"d1 > d3: {d1 > d3}")
print(f"d2 > d1: {d2 > d1}")
d1: 5 feet 5 inches
d2: 6 feet 2 inches
d3: 4 feet 8 inches

d1 < d2: True
d1 > d3: True
d2 > d1: True

How It Works

When you use comparison operators with custom objects, Python calls the corresponding magic methods ?

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def __lt__(self, other):
        print("__lt__ method called")
        return self.celsius < other.celsius

    def __gt__(self, other):
        print("__gt__ method called")
        return self.celsius > other.celsius

temp1 = Temperature(25)
temp2 = Temperature(30)

print(temp1 < temp2)  # Calls __lt__
print(temp1 > temp2)  # Calls __gt__
__lt__ method called
True
__gt__ method called
False

Complete Comparison Implementation

For a robust implementation, you can define all comparison operators ?

class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def __lt__(self, other):
        return self.score < other.score

    def __le__(self, other):
        return self.score <= other.score

    def __gt__(self, other):
        return self.score > other.score

    def __ge__(self, other):
        return self.score >= other.score

    def __eq__(self, other):
        return self.score == other.score

    def __ne__(self, other):
        return self.score != other.score

    def __str__(self):
        return f"{self.name}: {self.score}"

# Create student objects
alice = Student("Alice", 85)
bob = Student("Bob", 92)
charlie = Student("Charlie", 85)

print(f"alice < bob: {alice < bob}")
print(f"alice == charlie: {alice == charlie}")
print(f"bob >= alice: {bob >= alice}")
alice < bob: True
alice == charlie: True
bob >= alice: True

Key Points

  • Magic methods must return True or False for boolean comparisons
  • Converting objects to a common unit (like inches) ensures accurate comparison
  • Implementing __eq__ is important for equality testing
  • Python automatically provides opposite operators (e.g., if __lt__ is defined, > works in reverse)

Conclusion

Overloading comparison operators using magic methods like __lt__ and __gt__ allows custom objects to be compared naturally. Always ensure your comparison logic is consistent and returns boolean values for proper functionality.

Updated on: 2026-03-24T20:17:30+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements