Python Forum

Full Version: Creating a list of class objects
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello all,

I'm trying to create a list of different objects using a loop.
I expect to get a list of different objects. But, in fact, I get a list of same objects.

path = "C:/SomethingRandom/file.txt"
myList = []
with open(path, 'r', 8192, 'utf8') as input_file:
   while True:
       line = input_file.readline()
       if len(line) != 0:
           classObject = className()
           classObject.getData(line)
           myList.append(classObject)
          del classObject
       else:
           print("End of file!")
           break
So... As I've checked using printf(), in every loop iteration string "line" changes it's value. But myList containts as many copies of first object (created using first "line"), as many lines my .txt file has. I have no idea why it happens.
If I make a dummy class that just stores one instance attribute when getData is called, it works fine. I would expect the problem is in your classObject definition. Could be assigning to a class attribute by mistake?
(Jul-22-2017, 01:41 PM)ichabod801 Wrote: [ -> ]If I make a dummy class that just stores one instance attribute when getData is called, it works fine. I would expect the problem is in your classObject definition. Could be assigning to a class attribute by mistake?

The problem was in getData function. I used 3 lists in it, and I filled each of them using list.append(sth). No idea why, but when I declared these lists again in the function itself, everything started working perfectly.

Thanks a lot for answering!