Printing a list of objects of user defined class

So I have a class, called Vertex.

class Vertex:
    '''
    This class is the vertex class. It represents a vertex.
    '''

    def __init__(self, label):
        self.label = label
        self.neighbours = []

    def __str__(self):
        return("Vertex "+str(self.label)+":"+str(self.neighbours))

I want to print a list of objects of this class, like this:

x = [Vertex(1), Vertex(2)]
print x

but it shows me output like this:

[<__main__.Vertex instance at 0xb76ed84c>, <__main__.Vertex instance at 0xb76ed86c>]

Actually, I wanted to print the value of Vertex.label for each object.
Is there any way to do it?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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)

Method 2

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

Method 3

def __ str __ (self):
    return f"Vertex: {self.label} {self.neighbours}"

#In most cases, this is probably the easiest and cleanest way to do it. Not fully sure how this code will interact with your list []. Lastly, any words or commas needed, just add them between the brackets; no further quotes needed.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x