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

发布于 2021-01-29 19:10:25

所以我有一堂课,叫做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每个对象的值。有什么办法吗?

关注者
0
被浏览
50
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    print [vertex.label for vertex in x]
    

    但是要回答您的原始问题,您需要定义__repr__方法以正确获得列表输出。它可能像这样简单:

    def __repr__(self):
        return str(self)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看