【问题标题】:How to print a list consisting of custom class objects [duplicate]如何打印由自定义类对象组成的列表[重复]
【发布时间】:2016-11-04 12:00:30
【问题描述】:

假设我有一个自定义类:

class A:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return self.x + ',' + self.y

我可以通过这个得到预期的输出“x,y”:

sample = A('x', 'y')
print(sample)

但是如果我把样本放在一个列表中:

l = [sample]
print(l)

我知道了:

[<__main__.A object at 0x7ff8ae170470>]

我怎样才能得到预期的输出?

【问题讨论】:

  • 列表中的对象使用__repr__显示,而不是__str__

标签: python-3.x


【解决方案1】:

您需要为__repr__ 方法提供一个实现。您可以使用与 __str__ 方法相同的代码。

这篇文章涵盖了同样的内容并链接到文档:How to apply __str__ function when printing a list of objects in python

【讨论】:

    【解决方案2】:

    打印 '[%s]' % ', '.join(map(str, l))

    【讨论】:

    • 首先,适当地格式化您的代码示例。其次,提供一些解释,而不仅仅是简单的代码。此外,从标签来看,问题是关于 Python 3,所以你的打印方式行不通。请注意这一点
    • 这不是人们必须接受您的决定的地方,好吗?我测试了代码,这项工作你为什么要继续投票你不能提交但其他人可以提交的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2017-04-12
    • 1970-01-01
    相关资源
    最近更新 更多