简体   繁体   中英

Python - Appending to a list of an object declared inside a for loop

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM