我有一个简单的python类,我希望能够进行比较。所以我实现了比较运算符。然后我意识到我已经为很多类做了同样的事情,感觉很像代码重复。
class Foo(object):
def __init__(self, index, data):
self.index = index
self.data = data
def __lt__(self, other):
return self.index < other.index
def __gt__(self, other):
return self.index > other.index
def __le__(self, other):
return self.index <= other.index
def __ge__(self, other):
return self.index >= other.index
def __eq__(self, other):
return self.index == other.index
def __ne__(self, other):
return self.index != other.index
所以我认为一个简单的解决方案就是这样:
class Comparable(object):
def _compare(self, other):
raise UnimplementedError()
def __lt__(self, other):
return self._compare(other) < 0
def __gt__(self, other):
return self._compare(other) > 0
def __le__(self, other):
return self._compare(other) <= 0
def __ge__(self, other):
return self._compare(other) >= 0
def __eq__(self, other):
return self._compare(other) == 0
def __ne__(self, other):
return self._compare(other) != 0
class Foo1(Comparable):
def _compare(self, other):
return self.index - other.index
class Foo2(Comparable):
def _compare(self, other):
# ...
class Foo3(Comparable):
def _compare(self, other):
# ...
但它看起来很基本,我觉得我在这里重新发明轮子。
我想知道是否有更“原生”的方法来实现这一目标。
答案 0 :(得分:2)
正如in the docs所述,您可以使用functools.total_ordering
以书面形式保存一些样板
为了避免提供所有六个函数的麻烦,您可以实现
__eq__
,__ne__
,并且只能实现一个排序运算符,并使用functools.total_ordering()
装饰器来填充其余的。
要明确指出,他们所指的六个函数是:__eq__
,__ne__
,__lt__
,__le__
,__gt__
和{{1 }}
答案 1 :(得分:1)
因此,在创建丰富比较方法时,您需要一些自动化。您可以使用functools.total_ordering()
高阶函数来执行此操作。有关详细信息,请参阅reference。