更简单的方法来做python运算符重载?

dor*_*mon 0 python operator-overloading

我正在使用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
......
Run Code Online (Sandbox Code Playgroud)

我真的必须自己定义__lt __,__ eq __,__ ne __.它太冗长了.有更简单的方法可以解决这个问题吗?干杯.请不要使用__cmp__,因为它将在python 3中消失.

mgi*_*son 5

functools.total_ordering可以帮到你.它意味着是一个类装饰器.您定义的一个__lt__(),__le__(),__gt__(),或者__ge__() __eq__它在休息罢了.

作为旁注:

而不是写这个

if self.index <= other.index:
    return True
return False
Run Code Online (Sandbox Code Playgroud)

写这个:

return self.index <= other.index
Run Code Online (Sandbox Code Playgroud)

这样更干净.:-)