Printing a list of objects of user defined class

If you want a little more infos in addition of Daniel Roseman answer:

__repr__ and __str__ are two different things in python. (note, however, that if you have defined only __repr__, a call to class.__str__ will translate into a call to class.__repr__)

The goal of __repr__ is to be unambiguous. Plus, whenerver possible, you should define repr so that(in your case) eval(repr(instance)) == instance

On the other hand, the goal of __str__ is to be redeable; so it matter if you have to print the instance on screen (for the user, probably), if you don't need to do it, then do not implement it (and again, if str in not implemented will be called repr)

Plus, when type things in the Idle interpreter, it automatically calls the repr representation of your object. Or when you print a list, it calls list.__str__ (which is identical to list.__repr__) that calls in his turn the repr representaion of any element the list contains. This explains the behaviour you get and hopefully how to fix it


If you just want to print the label for each object, you could use a loop or a list comprehension:

print [vertex.label for vertex in x]

But to answer your original question, you need to define the __repr__ method to get the list output right. It could be something as simple as this:

def __repr__(self):
    return str(self)

Tags:

Python