Control equality and ordering by implementing rich comparison methods.
How It Works
__eq__(), __lt__(), and related methods express comparisons between objects. Return NotImplemented for unsupported operand types rather than raising arbitrary errors, allowing fallback comparison behavior.
functools.total_ordering can derive remaining ordering methods from a minimal set.
Step-by-Step Example
class Version:
def __init__(self, major_version, minor_version):
self.parts = (major_version, minor_version)
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.parts == other.parts
print(Version(3, 15) == Version(3, 15))
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
True
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Implement __lt__() using a tuple of numeric version components.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Returning NotImplementedError as though it were a comparison result.
- Overriding equality without considering the consequences for hashability.
Key Takeaways
- Control equality and ordering by implementing rich comparison methods.
- __eq__(), __lt__(), and related methods express comparisons between objects.
- functools.total_ordering can derive remaining ordering methods from a minimal set.