I am trying to print a list whose elements are all objects of a user defined class, as in this simple example:
class Athing:
def __init__(self,thething):
self.aray = thething
# Representation of thing for printing
def __str__(self):
return '['+ ', '. join(str(i) for i in self.aray) + ']'
this_thing = []
for j in range(2):
this_thing.append(Athing([[j,j+2,j+3], [j*2,j+5,j+6]]))
print 'this_thing =\n',this_thing
print 'this_thing[0] =\n',this_thing[0]
The code above gives me the following results:
this_thing =
[<__main__.Athing instance at 0x109dec368>, <__main__.Athing instance at 0x109dec3f8>]
this_thing[0] =
[[0, 2, 3], [0, 5, 6]]
Why can't the list of Athing
objects print them without explicitly asking for the object, as in the second print, and how can I make the first print work?
Printing a list containing objects uses __str__
for the list itself, but the implementation of list.__str__
calls __repr__
for each object - Athing() in your case.
So you want to override __repr__
and you won't have to override __str__
since :
If a class defines repr() but not str(), then repr() is also used when an “informal” string representation of instances of that class is required
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments