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(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/

相关文章:

python - 为什么 Python 的集差法对空集会耗时?

python - 为什么运行 setup.py,我可以嵌入代码吗?

python - 使用opencv的几何均值滤波器

python - 打开进度条直到功能任务结束

python - celery 异常处理

python - 如何使用 python 中的条件过滤 numpy 数组

python - wx.TextCtrl 中插入点位置的弹出菜单

python - 在 bash、R、python 或 NCL 中将 hdf5 转换为 netcdf4?

python - Numpy 图像 - 将矩阵旋转 270 度

python - 你如何从 Django PostgreSQL ArrayField 中获取字符串?