Reputation: 6854
Let us assume I have a class which implements the str() function. When I now put an object of this class into a dictionary and use str() of the dictionary, it does not use this function! What did I do wrong?
class test(object):
def __str__(self):
return("I am a dork")
a = test()
print(a)
X = {0:a}
print(str(tuple(sorted(X.items()))))
which returns:
I am a dork
((0, <__main__.test object at 0x7fe5204ddbe0>),)
Obviously, the goal would be to have
((0, 'I am a dork'),)
Upvotes: 1
Views: 35
Reputation: 1043
Try with:
class test(object):
def __str__(self):
return("I am a dork")
def __repr__(self):
return("I am a dork too")
Here repr doc
Upvotes: 0
Reputation: 1124828
Containers in Python show representations, not string conversions. You need to implement object.__repr__()
to influence the object representation.
Note that __str__
and __repr__
play different roles; the representation is there for debugging purposes, the __str__
string output for presentation. If __str__
is missing, __repr__
will be used, but not vice versa.
Upvotes: 3