我已经在python中编写了一个实现__str__(self)
但是当我在包含该类实例的列表上使用print时,我只获得了默认输出<__main__.DSequence instance at 0x4b8c10>
.我需要实现另一个神奇的功能才能使其工作,或者我是否必须编写自定义打印功能?
这是班级:
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]
Run Code Online (Sandbox Code Playgroud)
Pao*_*ino 23
是的,你需要使用__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__'
Run Code Online (Sandbox Code Playgroud)
但是,如果您没有定义__str__
,它会回退__repr__
,但不建议这样做:
>>> class Foo:
... def __repr__(self):
... return '__repr__'
...
>>> bar = Foo()
>>> bar
__repr__
>>> print bar
__repr__
Run Code Online (Sandbox Code Playgroud)
正如手册所建议的那样,所有考虑事项__repr__
都用于调试,并且应该返回repr
对象的某些内容.