Confused about __str__ on list in Python

Christofer Ohlsson picture Christofer Ohlsson · Sep 16, 2012 · Viewed 196.6k times · Source

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? :)

Answer

Sven Marnach picture Sven Marnach · Sep 16, 2012

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.