如何在 Python 中打印列表、字典或对象集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/875074/
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
How to print a list, dict or collection of objects, in Python
提问by Dana the Sane
I have written a class in python that implements __str__(self)
but when I use print on a list containing instances of this class, I just get the default output <__main__.DSequence instance at 0x4b8c10>
. Is there another magic function I need to implement to get this to work, or do I have to write a custom print function?
我在 python 中编写了一个实现类,__str__(self)
但是当我在包含此类实例的列表上使用 print 时,我只得到默认输出<__main__.DSequence instance at 0x4b8c10>
。是否需要实现另一个神奇的功能才能使其正常工作,或者我是否必须编写自定义打印功能?
Here's the class:
这是课程:
class DSequence:
def __init__(self, sid, seq):
"""Sequence object for a dummy dna string"""
self.sid = sid
self.seq = seq
def __iter__(self):
return self
def __str__(self):
return '[' + str(self.sid) + '] -> [' + str(self.seq) + ']'
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.seq[self.index]
回答by Paolo Bergantino
Yes, you need to use __repr__
. A quick example of its behavior:
是的,您需要使用__repr__
. 其行为的快速示例:
>>> class Foo:
... def __str__(self):
... return '__str__'
... def __repr__(self):
... return '__repr__'
...
>>> bar = Foo()
>>> bar
__repr__
>>> print bar
__str__
>>> repr(bar)
'__repr__'
>>> str(bar)
'__str__'
However, if you don't define a __str__
, it falls back to __repr__
, although this isn't recommended:
但是,如果您没有定义 a __str__
,它会回退到__repr__
,尽管不推荐这样做:
>>> class Foo:
... def __repr__(self):
... return '__repr__'
...
>>> bar = Foo()
>>> bar
__repr__
>>> print bar
__repr__
All things considered, as the manual recommends, __repr__
is used for debugging and should return something repr
esentative of the object.
正如手册所建议的那样,所有考虑的事情__repr__
都用于调试,并且应该返回repr
对象的某些内容。
回答by odwl
Just a little enhancement avoiding the + for concatenating:
只是一个小小的增强,避免了 + 连接:
def __str__(self):
return '[%s] -> [%s]' % (self.sid, self.seq)