The functools module in Python creates higher-order functions that interact with other functions. The higher-order functions either return other functions, or operate on them to broaden the scope of the function without modifying or explicitly defining them.
Comparison ordering methods of a class are used for the comparison of class objects. There are six comparison ordering methods for any given class. They are as follows:
__lt__()
: Lesser than method__le__()
: Lesser than or equal to method__gt__()
: Greater than method__ge__()
: Greater than or equal to method__eq__()
: Equal to methodtotal_ordering
descriptorLet’s imagine that we need to compare class objects. Hence, we have to provide the implementations of all the comparison ordering methods of the class. This requires a bit of effort.
However, we can simplify the process with the total_ordering
descriptor. We can define any one of the comparison ordering methods, and the decorator supplies the rest of the methods. The class also must provide an __eq__()
method.
Let’s consider we supply the __lt__
and __eq__
methods. The decorator supplies the rest of the comparison methods i.e., __le__()
, __gt__()
, and __ge__()
.
from functools import total_ordering@total_orderingclass Person:def __init__(self, age):self.age = agedef __lt__(self, other):return self.age < other.agedef __eq__(self, other):return self.age == other.ageperson1 = Person(10)person2 = Person(20)print("Person(10) > Person(20) ? ", person1 > person2)print("Person(10) == Person(20) ? ", person1 == person2)print("Person(10) >= Person(20) ? ", person1 >= person2)print("Person(10) < Person(20) ? ", person1 < person2)print("Person(10) <= Person(20) ? ", person1 <= person2)
total_ordering
decorator.Person
class decorated with total_ordering
. The class has age
as an attribute. We provide the implementations for the __lt__()
and __eq__()
methods considering the age
attribute.Person
objects called person1
and person2
, with a different value for the age
attributes of each.person1
and person2
using different comparison operators.