2011-08-23 38 views
1

为什么下面的代码在我添加了几个项目后返回空?python类像列表一样行为

class Con(list): 

    def __init__(self): pass 

    def __str__(self): 
     return ' '.join(self) 

    def add(self, value) 
     self.append(value) 

i for i in range(10): 
    Con().add(i) 

>>> print Con() 
# empty space instead of: 
0 1 2 3 4 5 6 7 8 9 

还有什么我必须定义为我的类表现得像一个列表?

回答

8

您总是在循环的每次迭代中创建一个新的con实例。您必须在循环前创建实例并添加到该实例。此外,你正在打印语句中创建另一个新实例,所以它也会变成空的。

+0

好啊,傻我。谢谢 – Shaokan

+0

...你缺少一个':'在线'def add(self,value)' –

5

您正在通过循环调用Con()来创建Con的11个实例,并且每次打印时都会再次调用Con()

你想要的东西,如:

c = Con() 
for i in range(10): 
    c.add(i) 

print c 
+0

Downvoter:关心评论我为什么错了? – geoffspear

2

的原因是,你不救CON的任何实例。在每个Con()上创建一个新实例。你必须把它保存在这样的地方:

c = Con() 
for i in range(10): 
    c.add(i) 

>>> print c 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
+0

你真的运行过吗? – NullUserException

+0

是的,我确实运行过它。 – Pit