[ACCEPTED]-How to print a list, dict or collection of objects, in Python-list
Accepted answer
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 repr
esentative of 1 the object.
Just a little enhancement avoiding the + for 1 concatenating:
def __str__(self):
return '[%s] -> [%s]' % (self.sid, self.seq)
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.