我正在尝试消除包含数千个自定义对象的数组的重复项。 为此,我正在为这些对象实现 __hash__ 和 __cmp__ 函数。
将这些函数委托(delegate)给对象的字段之一(保证唯一的字符串)是否安全?
即
class A:
def __init__(self, key, etc...):
self.key = key
...
def __hash__(self):
return self.key.__hash__()
def __cmp__(self, other):
return cmp(self.key, other.key)
# then somewhere in code with arr being array of A
unique = sorted(set(arr))
非常感谢任何提示!
请您参考如下方法:
避开 __cmp__。 Python3 no longer supports这种特殊方法,并建议改用 __lt__。
def __lt__(self,other):
return self.key < self.other
