[ACCEPTED]-How to print a list, dict or collection of objects, in Python-list

Accepted answer
Score: 24

Yes, you need to use __repr__. A quick example of 6 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 5 a __str__, it falls back to __repr__, although this isn't 4 recommended:

>>> class Foo:
...     def __repr__(self):
...             return '__repr__'
...
>>> bar = Foo()
>>> bar
__repr__
>>> print bar
__repr__

All things considered, as the 3 manual recommends, __repr__ is used for debugging 2 and should return something representative of 1 the object.

Score: 1

Just a little enhancement avoiding the + for 1 concatenating:

def __str__(self):
  return '[%s] -> [%s]' % (self.sid, self.seq)

More Related questions