Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Python
dictionary containing instances of classes behaving oddly
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Erik Johnson, post: 2051560"] I don't think I quite understand the confusion, and I think I might have said something misleading. The def statement itself is only executed once, as are any object initializers contained within it. Your record.__init__() is not using a default initializer, and here: class record: my_list =[] mops=[] def __init__(self,mops): self.mops=mops mops as the second argument to __init__ is a formal vairable, not a reference to record.mops. If you pass the same list reference to each constructor, then each record object shares the same list. You previously said: I had thought that then each time I created an instance of the record class as an element of my dictionary: self.mop_list[record_number]=record(self.mops[:]) I would create a brand new instance of the record class.It would have a mops list initialized with mops (because the def__init__ constructor is called when the class is instantiated), and an empty, individual list my_list. I beleive this is basically correct - by using the slice notation in self.mops[:] you are passing a copy of that list as the value. The difference is demonstrated here: .... X = [99] .... def __init__(self, X): # X is formal variable here, not Foo.X! .... self.X = X .... So, I guess I don't see exactly where the problem is, and without all your source, I am kinda poking in the dark. But from the behaviour observed in your record objects, you are obviously ending up with shared list references where you intend to get per-object individual lists. Generally the way to do that is to assign a new, empty list in the body of the object initializer and then populate that list as needed. Good luck. -ej [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Python
dictionary containing instances of classes behaving oddly
Top