Reputation: 13
I've made the following code trying to load from a newline seperated textfile. It stores apple objects made up of colour then size then kind (each on a newline). The weird thing is that the load function works but it returns all the loaded objects as identical to the last object loaded in (but it puts the correct number of objects in the list based on the lines in the textfile. The print near the append shows the correct data being read though for each object though...
I'm not sure what is wrong and how I rectify it?
def loadInApplesTheOtherWay(filename):
tempList = []
#make a tempList and load apples from file into it
with open(filename,"r") as file:
#file goes, colour \n size \n kind \n repeat...
lines = file.read().splitlines()
count = 1
newApple = apple()
for line in lines:
if count % 3 == 1:
newApple.colour = line
if count % 3 == 2:
newApple.size = line
if count % 3 == 0:
newApple.kind = line
tempList.append(newApple)
print(newApple)
count +=1
return tempList
Upvotes: 1
Views: 38
Reputation: 3818
newApple
is just a object reference.
>>> list(map(id, tempList))
The above line will show all apple is of the same id. As last modification of newApple
is at the file end, so tempList
are all the same as last apple object.
To make it differ, you need to deepcopy
the object, such as tempList.append(copy.deepcopy(newApple))
see https://docs.python.org/3/library/copy.html for more details.
Or you can create the object on the fly, you don't have to allocate newApple
before for loop.
def loadInApplesTheOtherWay(filename):
tempList = []
#make a tempList and load apples from file into it
with open(filename,"r") as file:
#file goes, colour \n size \n kind \n repeat...
lines = file.read().splitlines()
count = 1
for line in lines:
if count % 3 == 1:
colour = line
if count % 3 == 2:
size = line
if count % 3 == 0:
kind = line
newApple = Apple(colour, size, kind)
tempList.append(newApple)
print(newApple)
count +=1
return tempList
Upvotes: 1