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(),然後再版() 也用於需要該類的 實例的「非正式」字符串表示