0

I have searched SO and found numerous questions about this very topic, and I've tried recreating accepted answers, but I am unable to duplicate the output shown.

>>> class testFoo(object):
...     def __init__(self,x):
...         self.x = x
...     def __eq__(self, other):
...         return hash(self.x) == other
...     def __hash__(self):
...         return hash(self.x)
...
>>> d = {}
>>> x = testFoo("a")
>>> d[x] = 1
>>> d
{<__main__.testFoo object at 0x7f6d9ccc5550>: 1}
>>> hash(x)
12416037344
>>> hash("a")
12416037344
>>>

What I expected to see when I typed "d" above is a key "a", not the repr string for the object. What am I doing wrong?

1 Answer 1

1

That is because the key is the object and you haven't overriden the default __repr__.

You would need to add this to testFoo class.

def __repr__(self):
    return self.x
Sign up to request clarification or add additional context in comments.

1 Comment

doh! Thanks! Put in there, and it works as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.