开发者

python class act like a list

Why the following code returns empty after I have added several items in it?

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 

What else I have to define for my class to act 开发者_开发技巧like a list?


You're always creating a new instance of con in each iteration of your loop. You have to create the instance before the loop and add to that instance. Furthermore, you're creating another new instance in the print statement, so that'll turn up empty as well.


You're creating 11 instances of Con by calling Con() each time through the loop and again when you print.

You want something like:

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

print c


The reason is that you do not save any instance of con. On each Con() a new instance gets created. You have to save it somewhere like that:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜