Martynas Martynas - 1 year ago 76
Python Question

How to apply __str__ function when printing a list of objects in python

Well this interactive python console snippet will tell everything:

>>> class Test:
... def __str__(self):
... return 'asd'
>>> t = Test()
>>> print t
>>> l = [Test(), Test(), Test()]
>>> print l
[__main__.Test instance at 0x00CBC1E8, __main__.Test instance at 0x00CBC260,
__main__.Test instance at 0x00CBC238]

Basically I would like to get three 'asd' string printed when I print the list. I have also tried pprint but it gives the same results.

Answer Source


class Test:
   def __repr__(self):
       return 'asd'

And read this documentation link:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download