Ben
Ben

Reputation: 459

Trouble With Lists of Lists in Python

I'm brand new to python, but I have a lot of experience with C++, Java, and .NET. I'm hoping that someone can explain why this sample program works the way it does and how I can change it to work the way I would like it to work.

Essentially, I'm trying to create a list of objects, and each object in the list contains a list of objects. In the end, the sub lists are all the same list, instead of being unique to the instance of their parent class.

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

The output of the program:

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

Why don't the two Obj1 lists each have 2 items? Is there a better way to implement this?

Upvotes: 1

Views: 138

Answers (1)

HYRY
HYRY

Reputation: 97291

list_of_obj2 is a class attribute of Obj1, if you want instance attribute:

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

Upvotes: 8

Related Questions