[英]How to print a list, dict or collection of objects, in Python
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>
. 我在python中编写了一个实现__str__(self)
的类,但是当我在包含这个类的实例的列表上使用print时,我只得到默认输出<__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? 我需要实现另一个神奇的功能才能使其工作,或者我是否必须编写自定义打印功能?
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]
Yes, you need to use __repr__
. 是的,你需要使用__repr__
。 A quick example of its behavior: 它的行为的一个简单例子:
>>> 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: 但是,如果您没有定义__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
的对象esentative。
Just a little enhancement avoiding the + for concatenating: 只是一点点增强,避免连接+:
def __str__(self):
return '[%s] -> [%s]' % (self.sid, self.seq)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.