I'd like to represent an object as a string so that it can be accessed both as a dictionary key and as an object in itself. i.e.
class test(object):
def __init__(self, name, number_array):
self.name = name
self.number_array = number_array
self.graph= barChart(number_array)
sample_obj = test('test_object', [(x1,y1), (x2,y2)etc.])
but so that {sample_obj: another_object}
would look like {'test_object': another_object}
while still making something like this possible:
for key, val in sample_dict.items(): print(key.name, key.graph)
as well as:
>>> sample_dict['test_object']
another_object
To use a class as a dictionary key, implement
__hash__
and__eq__
. To change how it appears when you print the dictionary, implement__repr__
:In use:
Note that this means that both the
name
andnumber_array
attributes must be hashable - I have used a string and a tuple to ensure this. Also, it is better if__repr__
represents the actual object more closely, e.g.You must define eq that returns positive when comparing with the string i.e.:
You must also define hash that returns the same hash as the compared string:
UPDATE: The following code does exactly what the author wanted: