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
相关用法
- Python functools.wraps()用法及代码示例
- Python Functools update_wrapper()用法及代码示例
- Python Functools lru_cache()用法及代码示例
- Python Functools cached_property()用法及代码示例
注:本文由纯净天空筛选整理自sathiyajith19大神的英文原创作品 Python Functools – total_ordering()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。