Take this super simple class:
class Foo():
def __init__(self, iden):
self.iden = iden
def __hash__(self):
return hash(self.iden)
def __repr__(self):
return str(self.iden)
The goal is to create instances of the class to use as dict keys. If __repr__
is omitted, the keys are the standard object address. With __repr__
a printable representation might be:
f = Foo(1)
g = Foo(2)
d = {f:'a', g:'b'}
print(d)
>>> {1:'a', 2:'b'}
When attempting to access the dict by key though, it does not appear to be immediately obvious how to utilize the __repr__
(or __str__
for that matter) representation as the key.
print(d[1])
>>> KeyError