當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Functools total_ordering()用法及代碼示例


python中的Functools模塊有助於實現高階函數。高階函數是調用其他函數的從屬函數。 Total_ordering提供了豐富的類比較方法,這些方法可幫助比較類而不顯式定義其函數。因此,它有助於代碼的冗餘。

六種豐富的類比較方法是:

  • object.__lt__(self, other)
  • object.__le__(self, other)
  • object.__eq__(self, other)
  • object.__ne__(self, other)
  • object.__gt__(self, other)
  • 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 __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))

輸出



False
False
True
True
False
True

注意:自從__gt__ 方法未實現,它顯示“不

範例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




相關用法


注:本文由純淨天空篩選整理自sathiyajith19大神的英文原創作品 Python Functools – total_ordering()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。