【发布时间】:2018-04-11 11:14:57
【问题描述】:
我有一个简单的 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):
# ...
但它看起来很基础,我觉得我在这里重新发明了轮子。
我想知道是否有更“原生”的方式来实现这一点。
【问题讨论】:
-
对于像这样的基本操作,您可以简单地实现
__cmp__而不是每个单独的操作 -
@Jkdc 这正是我想要的!对 Python 3 的支持来说太糟糕了:(
标签: python