Pythontotal_ordering

示例

当我们想创建一个可订购类,通常我们需要定义方法__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起可用。