Python 打印用户定义类的对象列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12933964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing a list of objects of user defined class
提问by czardoz
So I have a class, called Vertex.
所以我有一个班级,叫做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>]
Actually, I wanted to print the value of Vertex.labelfor each object.
Is there any way to do it?
实际上,我想打印Vertex.label每个对象的值。有什么办法吗?
采纳答案by Daniel Roseman
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]
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:
但是要回答您的原始问题,您需要定义__repr__正确获得列表输出的方法。它可能是这样简单的事情:
def __repr__(self):
return str(self)
回答by Ant
If you want a little more infos in addition of Daniel Roseman answer:
如果除了 Daniel Roseman 之外,您还想了解更多信息,请回答:
__repr__and __str__are two different things in python. (note, however, that if you have defined only __repr__, a call to class.__str__will translate into a call to class.__repr__)
__repr__和__str__是python中的两个不同的东西。(但是,请注意,如果您只定义了__repr__,则对 的调用class.__str__将转换为对 的调用class.__repr__)
The goal of __repr__is to be unambiguous. Plus, whenerver possible, you should define repr so that(in your case) eval(repr(instance)) == instance
的目标__repr__是明确的。另外,只要可能,您应该定义 repr 以便(在您的情况下)eval(repr(instance)) == instance
On the other hand, the goal of __str__is to be redeable; so it matter if you have to print the instance on screen (for the user, probably), if you don't need to do it, then do not implement it (and again, if str in not implemented will be called repr)
另一方面,目标__str__是可重用;所以如果你必须在屏幕上打印实例(对于用户来说,可能)很重要,如果你不需要这样做,那么不要实现它(同样,如果没有实现 str 将被称为 repr )
Plus, when type things in the Idle interpreter, it automatically calls the repr representation of your object. Or when you print a list, it calls list.__str__(which is identical to list.__repr__) that calls in his turn the repr representaion of any element the list contains. This explains the behaviour you get and hopefully how to fix it
另外,当在 Idle 解释器中输入内容时,它会自动调用对象的 repr 表示。或者,当您打印列表时,它会调用list.__str__(与 相同list.__repr__),然后依次调用列表包含的任何元素的表示形式。这解释了你得到的行为,并希望如何解决它

