Python bug with dictionary
David C. Fox
davidcfox at post.harvard.edu
Mon Jul 21 20:42:29 EDT 2003
none wrote:
> or is it just me?
>
> I am having a problem with using a dictionary as an attribute of a
> class. This happens in python 1.5.2 and 2.2.2 which I am accessing
> through pythonwin builds 150 and 148 respectively
>
> In the sample code you see that I have class Item and class Dict
> class Dict contains a dictionary called items. The items dictionary
> will contain instances of Item that are keyed off of the Item name. In
> __main__ I create two distinct instances of Dict and 4 distinct
> instances of Item. By using the accessor method addItem() in Dict I add
> the instances of Item to Dict. In this case I add Item1 and Item2 to
> Dict1 and I add Item3 and Item4 to Dict2. When this is done I print
> out the instances of Dict and of Item. It appears that the dictionary
> items in each of the Dict instances is the exact same instance even
> though they were created as distinctly separate classes. The print out
> of the results shows them at the same memory address. The items
> dictionary inside of each Dict object have the same id when I do
> id(dict1.items) and id(dict2.items). This means that each of the items
> dictionary in the Dict instances has all four items in it, even though
> each should only have two. Apparently when I add the first to Item
> instances to dict1 and then the second two Item instances to dict2 they
> are being added to the same items dictionary.
By creating the attributes items and name in the body of class Dict, you
are creating class attributes which are shared by all instances of the
class. When addItem refers to self.items, it finds no instance
attribute, so it falls back to modifying the class attribute.
What you want to do instead is define
class Dict:
def __init__(self):
self.items = {}
self.name = ""
...
and similarly for Item
David
>
>
> class Dict:
> items = {}
> name = ""
>
> def addItem(self,item,name):
> self.items[name] = item
>
>
> def setName(self,name):
> self.name = name
>
> def getName(self):
> return self.name
>
> def printItemKeys(self):
> print "Dictonary Keys: ",self.items.keys()
>
More information about the Python-list
mailing list