0

我正在使用 Python 开发一个图形库,并且我正在以这种方式定义我的 vetex:

class Vertex:
def __init__(self,key,value):
    self._key = key
    self._value = value

@property
def key(self):
    return self._key

@key.setter
def key(self,newKey):
    self._key = newKey

@property
def value(self):
    return self._value

@value.setter
def value(self,newValue):
    self.value = newValue

def _testConsistency(self,other):
    if type(self) != type(other):
        raise Exception("Need two vertexes here!")

def __lt__(self,other):
    _testConsistency(other)
    if self.index <= other.index:
        return True
    return False
......

我真的必须自己定义 __lt__,__eq__,__ne__.... 吗?它是如此冗长。有没有更简单的方法可以解决这个问题?干杯。请不要使用 __cmp__ 因为它将在 python 3 中消失。

4

2 回答 2

5

functools.total_ordering可以在这里为您提供帮助。它应该是一个类装饰器。您定义、、 或AND__lt__()之一,它会填充其余部分。__le__()__gt__()__ge__() __eq__

作为旁注:

而不是写这个

if self.index <= other.index:
    return True
return False

写这个:

return self.index <= other.index

这样更干净。:-)

于 2013-01-10T19:22:49.187 回答
2

使用functools.total_ordering,您只需要定义一个相等运算符和一个排序运算符。在 Python < 3.2 中,您很不走运,必须将这些运算符定义为单独的方法。尽管您可以通过编写一个更简单的版本来节省一些代码total_ordering,但如果您在多个地方需要它。

于 2013-01-10T19:24:00.267 回答