I have a class with __str__ and __repr__ defined:
class MyClass:
def __init__(self, version):
self.version = version
def __repr__(self):
return self.version
myObjs = {}
o = MyClass("1")
myObjs[o] = o
print myObjs
Which prints:
{1: 1}
How do I store the MyClass object as value to the dictionary instead of the string representation?
I could have added getVersion(), but just wanted to know if there is some more elegant way.
Thanks
As mentioned in the comments, the dictionary is storing the object.
Prints the following:
The reason it prints this way is because the dictionary uses the
__repr__of its keys and values for both its__str__and__repr__functions. You can always change your__repr__function though to make it less ambiguous with an integer:Sample Output:
Feel free to use whichever format that works best for you. I also changed your class to extend from object to make it a new style class (it brings classes and types together in the language and adds additional abilities to classes (such as decorators and the super function)). Otherwise:
Outputs