【问题标题】:Printing a list of objects of user defined class打印用户定义类的对象列表
【发布时间】:2012-10-17 12:07:10
【问题描述】:

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

【问题讨论】:

    标签: python


    【解决方案1】:

    如果您只想打印每个对象的标签,您可以使用循环或列表推导:

    print [vertex.label for vertex in x]
    

    但要回答您最初的问题,您需要定义 __repr__ 方法来获得正确的列表输出。可以这么简单:

    def __repr__(self):
        return str(self)
    

    【讨论】:

    • 我觉得你需要这样写 print([vertex.label for vertex in x])
    【解决方案2】:

    如果您除了 Daniel Roseman 之外还想了解更多信息,请回答:

    __repr____str__ 在 python 中是两个不同的东西。 (但是请注意,如果您只定义了__repr__,则对class.__str__ 的调用将转换为对class.__repr__ 的调用)

    __repr__ 的目标是明确的。另外,只要有可能,您应该定义 repr 以便(在您的情况下)eval(repr(instance)) == instance

    另一方面,__str__ 的目标是可重复使用;所以如果你必须在屏幕上打印实例(可能是为了用户),如果你不需要这样做,那么就不要实现它(同样,如果 str in 未实现将被称为 repr)

    另外,当在 Idle 解释器中键入内容时,它会自动调用对象的 repr 表示。或者当您打印一个列表时,它会调用list.__str__(与list.__repr__ 相同),然后它会调用列表包含的任何元素的repr 表示。这解释了你得到的行为,并希望如何解决它

    【讨论】:

    • 我明白了,所以解释器在列表中的任何对象上递归调用 __repr__() .. 对吗?
    • 不,解释器正在调用 list.__str__() (或 repr,它取决于,但这是同一件事)并且 list.__str__ 返回一个字符串,该字符串由调用列表中所有对象的 repr 组成包含
    【解决方案3】:
    def __ str __ (self):
        return f"Vertex: {self.label} {self.neighbours}"
    
    #In most cases, this is probably the easiest and cleanest way to do it. Not fully sure how this code will interact with your list []. Lastly, any words or commas needed, just add them between the brackets; no further quotes needed.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-01
      • 1970-01-01
      • 2014-12-19
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      相关资源
      最近更新 更多