August 20th, 2011, 11:37 PM
Appending object to list overwrites previous
When I'm adding an object to a list of objects the object added overwrites the previous ones:
name = None
parent = None
lvl = 1
alist = 
#I load information from a site here, but it is irrelevant as it works
#and makes a list from it, the list is call lsUsers
for i in lsUsers:
user = User()
user.name = re.search("\<b\>(.*)\<\/b\>", i).group(1)
I've looked and it seems that the user variable is still referenced to the original objects as well, is there any way to fix this?
August 21st, 2011, 09:24 PM
This makes alist one variable across all instances of a class.
alist = 
to make one per instance.
self.alist = 
I can't really tell what your problem is from your description, but I think this might be it.
August 21st, 2011, 10:18 PM
That doesn't seem to help. Whats happening is that I'll have a few unique names that it's loading and getting, for example:
It will create the first object with the name attribute being "Bob". However, as it loops, all of the objects in the list are overwritten, so say the list is supposed to have objects like so:
[Bob, Jim, Frank] (these are what the name attribute should be)
However, I get:
[Frank, Frank, Frank]
Each object has its own location in memory, however they each have the same values as it goes through. I hope this explained it better.
August 22nd, 2011, 07:52 AM
The same thing applies to your User object - each new one is a new User object, but you've set them up to all share one name variable, and one parent, and one lvl, between them.
August 22nd, 2011, 03:38 PM
But if each is a new one that is created at that time, why are the attributes shared between them?
August 22nd, 2011, 06:18 PM
"Because your code tells it to create a new user object with shared attributes", is the literal answer. What you describe in words is something like this:
But what you've written in Python is something like this:
Each *user* is a new one created when you call User(), but the name, parent and level are not. They are the original ones created when Python processes your source code and reads the class User: section.
Each new user object has a bit inside it which says "name? point back to the User class to get the name. parent? point back to the User class to get the parent".
So you get a list of four User items, all sharing one name text. When you update one name, all four show the same name, because they are all told to store "name" in the same place in memory.
If you want it to not do that:
and that says "when creating a new User, create these things to go with it", so each time you create one user, you get a new space to put the name, a new place to put the parent, etc.
self.name = ""
self.parent = ""
self.lvl = ""
Comments on this post
Last edited by sfb; August 22nd, 2011 at 06:21 PM.
August 23rd, 2011, 03:42 AM
Ah alright that makes perfect sense now! The diagrams made it a lot more obvious to me. Thank you for your help