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!
-
Or this one: stackoverflow.com/questions/15489567/…mgilson– mgilson2013年03月20日 19:28:09 +00:00Commented 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.toficofi– toficofi2013年03月20日 19:31:35 +00:00Commented Mar 20, 2013 at 19:31
-
You will find precise explanation in this answer of me: (stackoverflow.com/a/15467310/551449)eyquem– eyquem2013年03月20日 20:07:12 +00:00Commented Mar 20, 2013 at 20:07
2 Answers 2
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 = []
Comments
somelist is a class variable, so it's identical for every instance.