2

I'm having a very specific problem that I could not find the answer to anywhere on the web. I'm new to python code (C++ is my first language), so I'm assuming this is just a semantic problem. My question is regarding objects that are declared inside the scope of a for loop.

The objective of this code is to create a new temporary object inside the for loop, add some items to it's list, then put the object into a list outside of the for loop. At each iteration of the for loop, I wish to create a NEW, SEPARATE object to populate with items. However, each time the for loop executes, the object's list is already populated with the items from the previous iteration.

I have a bigger program that is having the same problem, but instead of including a massive program, I wrote up a small example which has the same semantic problem:

#Test

class Example:
    items = []

objList = []

for x in xrange(5):
    Object = Example()

    Object.items.append("Foo")
    Object.items.append("Bar")
    print Object.items

    objList.append(Object)

print "Final lists: "
for x in objList:
    print x.items

By the end of the program, every item in objList (even the ones from the first iterations) contains

["Foo","Bar","Foo","Bar","Foo","Bar","Foo","Bar","Foo","Bar"]`

This leads me to believe the Example (called Object in this case) is not recreated in each iteration, but instead maintained throughout each iteration, and accessed every time the for loop continues.

My simple question; in python, how to I change this?

0

2 Answers 2

3

Change your class definition to:

class Example:
    def __init__(self):
        self.items = []

The problem is that items is not being bound to the instance of each object, it is a part of the class definition. Because items is a class variable, it is shared between the instances of Example.

Sign up to request clarification or add additional context in comments.

1 Comment

This fixes my problem, thank you! I had no idea class wide variables existed.
2

Your class Example is using a class variable Example.items to store the strings. Class variables are shared across all instances of the objects which is why you're getting them all together and thinking it's the same object when in fact, it is not.

You should create the items variable and assign it to self in your __init__ function

class Example(object):

    def __init__(self):
        self.items = []

This will ensure that each instance of Example has its own items list to work with.

Also, as you're using Python 2.x, you really should subclass object as I have there.

1 Comment

Same as the other person, this fixes my problem. Now I know about object-shared variables.

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.