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.
But when I do the following:
uno.neighbours.append([[due, 4], [tri, 5]])
[[[<__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:
repr(). Printing an object uses
str(); printing a list containing an object uses
str() for the list itself, but the implementation of
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.
__str__, the other is
__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
When printing lists as well as other container classes, the contained elements will be printed using