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

我有一门课,叫 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>]

实际上,我想为每个对象打印 Vertex.label的值。 有什么办法吗?

98014 次浏览

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

print [vertex.label for vertex in x]

但是要回答最初的问题,您需要定义 __repr__方法来获得正确的列表输出。可能就是这么简单:

def __repr__(self):
return str(self)

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

在 python 中,__repr____str__是两种不同的东西。(但是请注意,如果您只定义了 __repr__,那么对 class.__str__的调用将转换为对 class.__repr__的调用)

__repr__的目标是明确无误的。另外,只要可能,你应该定义 repr,以便(在你的情况下) eval(repr(instance)) == instance

另一方面,__str__的目标是可重写的; 因此,如果你必须在屏幕上打印实例(可能是为了用户) ,如果你不需要这样做,那么就不要实现它(同样,如果 str 在未实现的情况下将被称为 repr) ,这很重要

另外,当在 Idle 解释器中输入内容时,它会自动调用对象的 repr 表示。或者当你打印一个列表时,它调用 list.__str__(与 list.__repr__完全相同) ,它依次调用列表包含的任何元素的 repr 表示。这解释了你的行为,并希望如何解决它

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.