@functools.total_ordering
class decorator in Python supplies comparison
ordering methods for a given class, provided
the given class satisfies below conditions.
__eq__()
method.__lt__(), __le__(), __gt__(), or __ge__()
methods.lets understand this with below example, where class Student
implements __eq__()
and
__lt__
comparison method and
rest of the comparison ordering methods are being supplied by @functools.total_ordering
class
decorator.
from functools import total_ordering
@total_ordering
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def _is_valid_operand(self, other):
return hasattr(other, "name") and hasattr(other, "age")
def __eq__(self, other):
if not self._is_valid_operand(other):
return NotImplemented
return self.age == other.age
def __lt__(self, other):
if not self._is_valid_operand(other):
return NotImplemented
return self.age < other.age
student1 = Student("xyz", 23)
student2 = Student("abc", 25)
print(student1 == student2)
print(student1 > student2)
print(student1 < student2)
# Output
False
False
True
Similar Articles