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!

toficofi
  • 583
  • 6
  • 24
  • Or this one: http://stackoverflow.com/questions/15489567/all-instances-of-a-class-have-the-same-dict-as-an-attribute-in-python-3-2 – mgilson Mar 20 '13 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. – toficofi Mar 20 '13 at 19:31
  • You will find precise explanation in this answer of me: (http://stackoverflow.com/a/15467310/551449) – eyquem Mar 20 '13 at 20:07

2 Answers2

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 = []
J0HN
  • 26,063
  • 5
  • 54
  • 85
1

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

uselpa
  • 18,732
  • 2
  • 34
  • 52
  • Thanks for further clarifying this. My previous experience with C++/Java etc tripped me up on this. – toficofi Mar 20 '13 at 19:30