打印用户定义类的对象列表 [英] Printing a list of objects of user defined class
本文介绍了打印用户定义类的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个类,叫做Vertex
.
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>]
实际上,我想为每个对象打印 Vertex.label
的值.有什么办法吗?
Actually, I wanted to print the value of Vertex.label
for each object.
Is there any way to do it?
推荐答案
如果只想打印每个对象的标签,可以使用循环或列表推导式:
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]
但是要回答您原来的问题,您需要定义 __repr__
方法来获得正确的列表输出.它可能是这样简单的:
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)
这篇关于打印用户定义类的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文