這裏是我的代碼:如何使對象正常排列?
class Hero:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name + str(self.age)
def __hash__(self):
print(hash(str(self)))
return hash(str(self))
heroes = set()
heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
print(len(heroes)) # gets 1
heroes.add(Hero('Lara Miheenko', 17)) # gets hash -2822451113328084695
print(len(heroes)) # gets 2
heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
print(len(heroes)) # gets 3! WHY?
這究竟是爲什麼?
第1個和第3個對象具有相同的內容和相同的散列,但len()
講述了3個獨特的對象?
不知道,但你可能需要'__eq__'或'__cmp__' :http://docs.python.org/glossary.html#term-hashable – nhahtdh
除此之外,這不是最好的散列函數(因爲你不是散列一個普通的字符串,其中一個字符串組件的熵低得多因爲它已知由數字組成)。對於一個微不足道但非常有效的修復方法,分別取對象的哈希值並將其與xor進行比較。要獲得更多魔法,請將它們添加爲由素數常量縮放。 –
@KonradRudolph:你的評論中有一個隱含的假設 - 特別需要一個「好」的散列才能讓這個集合表現出色。 Python的'set'實現並非如此;請參閱[來自Python源代碼的此評論](http://hg.python.org/cpython/file/26e2ee402a0b/Objects/dictobject.c#l113)以獲取更多解釋。 –