Custom Comparison Methods
Introduction to Special Comparison Methods
Python allows custom classes to define their own comparison behaviors through special methods:
Special Method |
Description |
Operator |
__eq__() |
Equal to |
== |
__ne__() |
Not equal to |
!= |
__lt__() |
Less than |
< |
__gt__() |
Greater than |
> |
__le__() |
Less than or equal |
<= |
__ge__() |
Greater than or equal |
>= |
Implementing Custom Comparison
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
if not isinstance(other, Person):
return NotImplemented
return self.name == other.name and self.age == other.age
def __lt__(self, other):
if not isinstance(other, Person):
return NotImplemented
return self.age < other.age
## Usage example
person1 = Person("Alice", 30)
person2 = Person("Alice", 30)
person3 = Person("Bob", 25)
print(person1 == person2) ## True
print(person1 < person3) ## False
Comparison Method Workflow
graph TD
A[Comparison Request] --> B{Check Instance Type}
B --> |Valid Type| C[Execute Comparison Method]
B --> |Invalid Type| D[Return NotImplemented]
C --> E[Return Comparison Result]
from functools import total_ordering
@total_ordering
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def __eq__(self, other):
return self.grade == other.grade
def __lt__(self, other):
return self.grade < other.grade
## Automatically generates other comparison methods
student1 = Student("Alice", 85)
student2 = Student("Bob", 90)
print(student1 < student2) ## True
print(student1 <= student2) ## True
Best Practices
- Always handle type checking
- Return
NotImplemented
for incompatible types
- Use
@total_ordering
for comprehensive comparisons
- Consider performance implications
Comparison with Built-in Types
class CustomNumber:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, (int, float)):
return self.value == other
return self.value == other.value
## Flexible comparison
num = CustomNumber(5)
print(num == 5) ## True
print(num == 5.0) ## True
LabEx Recommendation
At LabEx, we emphasize the importance of implementing robust and type-safe comparison methods in custom classes.