Coming from a Java background, I understand that __str__
is something like a Python version of toString (while I do realize that Python is the older language).
So, I have defined a little class along with an __str__
method as follows:
class Node:
def __init__(self, id):
self.id = id
self.neighbours = []
self.distance = 0
def __str__(self):
return str(self.id)
I then create a few instances of it:
uno = Node(1)
due = Node(2)
tri = Node(3)
qua = Node(4)
Now, the expected behaviour when trying to print one of these objects is that it's associated value gets printed. This also happens.
print uno
yields
1
But when I do the following:
uno.neighbours.append([[due, 4], [tri, 5]])
and then
print uno.neighbours
I get
[[[<__main__.Node instance at 0x00000000023A6C48>, 4], [<__main__.Node instance at 0x00000000023A6D08>, 5]]]
Where I expected
[[2, 4], [3, 5]]
What am I missing? And what otherwise cringe-worthy stuff am I doing? :)
Python has two different ways to convert an object to a string: str()
and repr()
. Printing an object uses str()
; printing a list containing an object uses str()
for the list itself, but the implementation of list.__str__()
calls repr()
for the individual items.
So you should also overwrite __repr__()
. A simple
__repr__ = __str__
at the end of the class body will do the trick.
Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.
One is __str__
, the other is __repr__
__str__
will return a human readable string.
__repr__
will return an internal representation.
__repr__
can be invoked on an object by calling repr(obj)
or by using backticks `obj`
.
When printing lists as well as other container classes, the contained elements will be printed using __repr__
.