22

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?

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]
Dana the Sane
  • 14,762
  • 8
  • 58
  • 80

2 Answers2

24

Yes, you need to use __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:

>>> 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 representative of the object.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • Is it worth conforming to what the manual says "If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment)." So something like DSequence(1, 'GTTAC')? – Dana the Sane May 17 '09 at 17:43
  • Ok, I also found this q for that http://stackoverflow.com/questions/452300/python-object-reprself-should-be-an-expression Thanks for your help. – Dana the Sane May 17 '09 at 17:47
  • 1
    BTW, why do containers use repr() to print elements? Should I use it too for my own containers? – Bastien Léonard May 17 '09 at 18:11
1

Just a little enhancement avoiding the + for concatenating:

def __str__(self):
  return '[%s] -> [%s]' % (self.sid, self.seq)
tzot
  • 92,761
  • 29
  • 141
  • 204
odwl
  • 2,095
  • 2
  • 17
  • 15