所以我有一个类,叫做 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
的值。
有什么办法吗?
最佳答案
如果您只想打印每个对象的标签,您可以使用循环或列表推导:
print [vertex.label for vertex in x]
但要回答您最初的问题,您需要定义 __repr__
方法以正确获取列表输出。可以这么简单:
def __repr__(self):
return str(self)
关于python - 打印用户定义类的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12933964/