1

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?

1
  • 1
    Think of your declared variable as a static variable in Java. If you want object variables you need to define them in init as HYRY said. Commented Aug 18, 2011 at 7:33

1 Answer 1

8

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

class Obj1(object):
    def __init__(self):
        self.list_of_obj2 = []
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.