Python Functools – total_ordering()
Functools module in python helps in implementing higher-order functions. Higher-order functions are dependent functions that call other functions. Total_ordering provides rich class comparison methods that help in comparing classes without explicitly defining a function for it. So, It helps in the redundancy of code.
The six rich class comparison methods are:
- object.__lt__(self, other)
- object.__le__(self, other)
- object.__eq__(self, other)
- object.__ne__(self, other)
- object.__gt__(self, other)
- object.__ge__(self, other)
There are 2 essential conditions to implement these comparison methods:
- At least one of the comparison methods must be defined from lt(less than), le(less than or equal to), gt(greater than) or ge(greater than or equal to).
- The eq function must also be defined.
Example:
from functools import total_ordering @total_orderingclass Students: def __init__(self, cgpa): self.cgpa = cgpa def __lt__(self, other): return self.cgpa<other.cgpa def __eq__(self, other): return self.cgpa == other.cgpa def __le__(self, other): return self.cgpa<= other.cgpa def __ge__(self, other): return self.cgpa>= other.cgpa def __ne__(self, other): return self.cgpa != other.cgpa Arjun = Students(8.6) Ram = Students(7.5) print(Arjun.__lt__(Ram))print(Arjun.__le__(Ram))print(Arjun.__gt__(Ram))print(Arjun.__ge__(Ram))print(Arjun.__eq__(Ram))print(Arjun.__ne__(Ram)) |
Output
False False True True False True
Note: Since the __gt__ method is not implemented, it shows “Not
Example 2:
from functools import total_ordering @total_orderingclass num: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.value def __eq__(self, other): # Changing the functionality # of equality operator return self.value != other.value # Driver codeprint(num(2) < num(3))print(num(2) > num(3))print(num(3) == num(3))print(num(3) == num(5)) |
Output:
True False False True


