📜  Python Functools – total_ordering()

📅  最后修改于: 2022-05-13 01:55:09.903000             🧑  作者: Mango

Python Functools – total_ordering()

Python中的 Functools 模块有助于实现高阶函数。高阶函数是调用其他函数的依赖函数。 Total_ordering 提供了丰富的类比较方法,可以帮助比较类,而无需为其显式定义函数。因此,它有助于代码的冗余。

六种富类比较方法是:

  • 对象.__lt__(自我,其他)
  • object.__le__(self, other)
  • object.__eq__(self, other)
  • object.__ne__(self, other)
  • 对象.__gt__(自我,其他)
  • object.__ge__(self, other)

实现这些比较方法有两个基本条件:

  • 必须从lt(小于)、le(小于或等于)、gt(大于)或ge(大于或等于)中定义至少一种比较方法。
  • eq函数也必须定义。

例子:

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 __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))

输出

False
False
True
True
False
True

注意:由于__gt__方法没有实现,所以显示“Not

示例 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))

输出:

True
False
False
True