Here is my code:
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?
Why is this happening?
The 1st and the 3rd object have same content and same hash but len()
tells about 3 unique objects?
__eq__
or__cmp__
: docs.python.org/glossary.html#term-hashableset
implementation; see this comment from the Python sources for further explanations.hash((self.name, self.age))
, deferring the details to the tuple hash algorithm of the Python implementation, which is hopefully optimised to work well with theset
anddict
implementations. And I agree that the linked comment is not a rigorous analysis. I find it interesting anyway; extensive and thorough benchmarking, as has been performed for the CPythondict
implementation, might lead to better performance in practice than a rigorous analysis.