67

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?

4

3 回答 3

94

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)
于 2012-10-17T12:10:17.763 回答
17

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

于 2012-10-17T12:28:25.973 回答
0
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.
于 2020-09-19T13:16:55.500 回答