Python Forum
Creating a list of class objects - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Creating a list of class objects (/thread-4095.html)



Creating a list of class objects - hjuyrfc - Jul-22-2017

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.


RE: Creating a list of class objects - ichabod801 - Jul-22-2017

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?


RE: Creating a list of class objects - hjuyrfc - Jul-22-2017

(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!