Open In App

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:



There are 2 essential conditions to implement these comparison methods:

Example:




from functools import total_ordering
  
  
@total_ordering
class 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_ordering
class 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 code
print(num(2) < num(3))
print(num(2) > num(3))
print(num(3) == num(3))
print(num(3) == num(5))

Output:

True
False
False
True

Article Tags :