麻烦的Python列表列表

时间:2011-08-18 03:18:20

标签: python

我是python的新手,但我在C ++,Java和.NET方面有很多经验。我希望有人可以解释为什么这个示例程序的工作方式以及如何将其更改为按照我希望的方式工作。

基本上,我正在尝试创建一个对象列表,列表中的每个对象都包含一个对象列表。最后,子列表都是相同的列表,而不是它们的父类实例的唯一。

class Obj1(object):
    list_of_obj2 = []
    name = ''

class Obj2(object):
    name = ''

list_of_obj1 = []

for i in range(2):
    new_obj1 = Obj1()
    new_obj1.name = "obj1_%s" % i
    print "Creating Object1 named %s" % new_obj1.name

    for j in range(2):
        new_obj2 = Obj2()
        new_obj2.name = "...obj2_%s_%s" % (i, j)

        new_obj1.list_of_obj2.append(new_obj2)
        print "...Added Object2 named %s to %s list" % (new_obj2.name, new_obj1.name)

    list_of_obj1.append(new_obj1)
    print "Added Object1 named %s to master list" % (new_obj1.name)

print ""

for obj in list_of_obj1:
    print "%s has %s items in list" % (obj.name, len(obj.list_of_obj2))
    for obj2 in obj.list_of_obj2:
        print "...%s" % obj2.name

该计划的输出:

Creating Object1 named obj1_0
...Added Object2 named ...obj2_0_0 to obj1_0 list
...Added Object2 named ...obj2_0_1 to obj1_0 list
Added Object1 named obj1_0 to master list
Creating Object1 named obj1_1
...Added Object2 named ...obj2_1_0 to obj1_1 list
...Added Object2 named ...obj2_1_1 to obj1_1 list
Added Object1 named obj1_1 to master list

obj1_0 has 4 items in list
......obj2_0_0
......obj2_0_1
......obj2_1_0
......obj2_1_1
obj1_1 has 4 items in list
......obj2_0_0
......obj2_0_1
......obj2_1_0
......obj2_1_1

为什么两个Obj1列表每个都没有2项?有没有更好的方法来实现这个?

1 个答案:

答案 0 :(得分:8)

list_of_obj2是Obj1的类属性,如果你想要实例属性:

class Obj1(object):
    def __init__(self):
        self.list_of_obj2 = []