class A():
def __init__(self, data=''):
self.data = data
def __str__(self):
return str(self.data)
d = {}
elem = A()
d[elem] = 'abc'
elem2 = A()
print d[elem2] # KeyError
# actually elem2! was used not elem
how can I implement this without error?
I tried to get d[elem2] (not elem) with another instance of A() BUT with the same content.
The answer is yes, you need to redefine
__hash__()and__eq__():As explained in another comment default implementation of
__hash__is just simple identity, so if you want to make it more sophisticated, you need to define it explicitly.