2014-09-06 64 views
0

我想打印其元素是用户定义的类的所有对象的列表,在这个简单的例子列表:打印的元素是类对象

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] 

上面的代码给我下面的结果:

this_thing = 
[<__main__.Athing instance at 0x109dec368>, <__main__.Athing instance at 0x109dec3f8>] 
this_thing[0] = 
[[0, 2, 3], [0, 5, 6]] 

为什么不能Athing对象名单打印出来,而不明确 要求的对象,如第二打印,以及如何才能让 第一个打印的工作?

+5

您还需要定义'__repr__'。 – 2014-09-06 13:52:57

回答

1

打印包含对象的列表使用__str__作为列表本身,但实现list.__str__为每个对象调用__repr__ -Athing()在您的情况下。

所以要覆盖__repr__,你将不必重写__str__因为:

如果一个类定义再版(),但不STR(),然后再版() 也用于需要该类的 实例的“非正式”字符串表示