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_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):
return self.value != other.value
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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Mar, 2020
Like Article
Save Article