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 FooBar
s.
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!