总订货量
当我们想要创建一个可订购的类时,通常我们需要定义方法 __eq()__,__lt__(),__le__(),__gt__() 和 __ge__()。
应用于类的 total_ordering 装饰器允许定义 __eq__(),__lt__(),__le__(),__gt__() 和 __ge__() 之间只有一个,并且仍然允许该类的所有排序操作。
@total_ordering
class Employee:
...
def __eq__(self, other):
return ((self.surname, self.name) == (other.surname, other.name))
def __lt__(self, other):
return ((self.surname, self.name) < (other.surname, other.name))
装饰器使用所提供方法和代数运算的组合来导出其他比较方法。例如,如果我们定义 __lt__() 和 __eq()__ 并且我们想要派生 __gt__(),我们可以简单地检查 not lt()and not__eq()__。
注意 :total_ordering 函数仅在 Python 2.7 之后可用。