Python 打印用户定义类的对象列表

Python 打印用户定义类的对象列表,python,Python,所以我有一个类,叫做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(se

所以我有一个类,叫做
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))
我想打印此类对象的列表,如下所示:

x = [Vertex(1), Vertex(2)]
print x
[<__main__.Vertex instance at 0xb76ed84c>, <__main__.Vertex instance at 0xb76ed86c>]
但它向我显示了如下输出:

x = [Vertex(1), Vertex(2)]
print x
[<__main__.Vertex instance at 0xb76ed84c>, <__main__.Vertex instance at 0xb76ed86c>]
[,]
实际上,我想为每个对象打印
Vertex.label
的值。
有什么办法吗?

如果只想打印每个对象的标签,可以使用循环或列表:

print [vertex.label for vertex in x]
但要回答最初的问题,您需要定义
\uuu repr\uuu
方法以获得正确的列表输出。可以是这么简单的事情:

def __repr__(self):
    return str(self)

如果您想了解更多关于Daniel Roseman的信息,请回答:

\uuuu repr\uuuu
\uuu str\uuuu
在python中是两个不同的东西。(但是,请注意,如果您只定义了
\uuuu repr\uuuu
,那么对
类的调用将转换为对
类的调用

\uuuu repr\uuuu
的目标是明确无误。另外,如果可能,您应该定义repr,以便(在您的情况下)
eval(repr(instance))==instance

另一方面,
\uuuu str\uuu
的目标是可重新定义;因此,如果您必须在屏幕上打印实例(可能是针对用户),如果您不需要这样做,那么就不要实现它(同样,如果str in not implemented将被称为repr),这很重要


另外,当在空闲解释器中键入内容时,它会自动调用对象的repr表示。或者当你打印一个列表时,它调用
list.\uu str\uuuuu
(这与
list.\uuu repr\uuuu
)依次调用列表包含的任何元素的repr表示。这解释了您得到的行为,以及希望如何修复它

我明白了,因此解释器在列表中的任何对象上递归调用_repr_;()。。是吗?不,解释器正在调用list.\uuuu str\uuuuuuuuuuuuuuuuuuuuuuuuuu()(或者repr,这取决于,但这是同一件事)和list.\uuuuu str\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu返回一个字符串,该字符串由调用repr组成,该列表包含的所有对象我认为需要像这样编写([vertex
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.