0

I'm getting some strange behavior with Python 2.7.2.

If I have dictionary of classes, any lists inside those classes remain with the same value through all the class instances in the containing dictionary.

This will explain what I mean:

>>> class FooBar():
 somelist = []
>>> someFooBars = {}
>>> someFooBars["key1"] = FooBar()
>>> someFooBars["key2"] = FooBar()
>>> someFooBars["key3"] = FooBar()
>>> someFooBars["key1"].somelist.append("Hello")
>>> someFooBars["key1"].somelist
['Hello']
>>> someFooBars["key2"].somelist
['Hello']
>>> someFooBars["key1"].somelist.append("World!")
>>> someFooBars["key3"].somelist
['Hello', 'World!']

As you can see, I have filled the dictionary with three instances of FooBar, keyed with strings, but once I add objects to somelist, the objects are also in the other FooBars.

This isn't what I expect to happen (I expect them to be separate) but there is obviously a reason - please explain what this reason is, why this happens, and how I would fix it. Thanks!

asked Mar 20, 2013 at 19:24
3
  • Or this one: stackoverflow.com/questions/15489567/… Commented Mar 20, 2013 at 19:28
  • @PavelAnossov: You're correct, and I am sorry for making a duplicate - I did search beforehand but I obviously didn't use the correct terminology. Commented Mar 20, 2013 at 19:31
  • You will find precise explanation in this answer of me: (stackoverflow.com/a/15467310/551449) Commented Mar 20, 2013 at 20:07

2 Answers 2

1

What you have now is some kind of "static" member. To achieve "instance" member behavior, add __init__ method (serves as "constructor"):

class FooBar():
 def __init__(self):
 self.somelist = []
answered Mar 20, 2013 at 19:26
Sign up to request clarification or add additional context in comments.

Comments

1

somelist is a class variable, so it's identical for every instance.

answered Mar 20, 2013 at 19:28

1 Comment

Thanks for further clarifying this. My previous experience with C++/Java etc tripped me up on this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.