473,574 Members | 2,683 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python bug with dictionary

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.

If I assign the Item instances to the items dictionary without using the
accessor method this does not occur. I have also tried a test with
lists with and without accessor method. This works fine also. The
simple solution is not to use accessor method but shouldn't this work?

Dale
class Dict:
items = {}
name = ""

def addItem(self,it em,name):
self.items[name] = item
def setName(self,na me):
self.name = name

def getName(self):
return self.name

def printItemKeys(s elf):
print "Dictonary Keys: ",self.items.ke ys()
class Item:
name = ""

def getName(self):
return self.name

def setName(self,na me):
self.name = name
if __name__ == '__main__':

dict1 = Dict()
dict1.setName(" dict1")

dict2 = Dict()
dict2.setName(" dict2")

item1 = Item()
item1.setName(" item1")

item2 = Item()
item2.setName(" item2")

item3 = Item()
item3.setName(" item3")

item4 = Item()
item4.setName(" item4")

print "Item 1: ",item1
print "Item 2: ",item2
print "Item 3: ",item3
print "Item 4: ",item4

print "\n"

dict1.addItem(i tem1,item1.getN ame())
dict1.addItem(i tem2,item2.getN ame())

dict2.addItem(i tem3,item3.getN ame())
dict2.addItem(i tem4,item4.getN ame())

print "Dictionary Object: ",dict1
print "Dictionary Name: ",dict1.getName ()
dict1.printItem Keys()
print "Dictionary Keys: ",dict1.items.k eys()
print "Dictionary Item Objects: ",dict1.ite ms
print "\n"
print "Dictionary Object: ",dict2
print "Dictionary Name: ",dict2.getName ()
dict2.printItem Keys()
print "Dictionary Keys: ",dict2.items.k eys()
print "Dictionary Item Objects: ",dict2.ite ms
print "\n"
print "ID of items in dict1: " + str(id(dict1.it ems))
print "ID of itmes in dict2: " + str(id(dict2.it ems))

Item 1: <__main__.Ite m instance at 0x00778F20>
Item 2: <__main__.Ite m instance at 0x00779240>
Item 3: <__main__.Ite m instance at 0x00779518>
Item 4: <__main__.Ite m instance at 0x00779820>
Dictionary Object: <__main__.Dic t instance at 0x00778BE8>
Dictionary Name: dict1
Dictonary Keys: ['item2', 'item3', 'item1', 'item4']
Dictionary Keys: ['item2', 'item3', 'item1', 'item4']
Dictionary Item Objects: {'item2': <__main__.Ite m instance at
0x00779240>, 'i
tem3': <__main__.Ite m instance at 0x00779518>, 'item1': <__main__.Ite m
instance
at 0x00778F20>, 'item4': <__main__.Ite m instance at 0x00779820>}
Dictionary Object: <__main__.Dic t instance at 0x00778BB0>
Dictionary Name: dict2
Dictonary Keys: ['item2', 'item3', 'item1', 'item4']
Dictionary Keys: ['item2', 'item3', 'item1', 'item4']
Dictionary Item Objects: {'item2': <__main__.Ite m instance at
0x00779240>, 'i
tem3': <__main__.Ite m instance at 0x00779518>, 'item1': <__main__.Ite m
instance
at 0x00778F20>, 'item4': <__main__.Ite m instance at 0x00779820>}
ID of items in dict1: 8016928
ID of itmes in dict2: 8016928

Jul 18 '05 #1
1 3577
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,it em,name):
self.items[name] = item
def setName(self,na me):
self.name = name

def getName(self):
return self.name

def printItemKeys(s elf):
print "Dictonary Keys: ",self.items.ke ys()


Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
2824
by: Don Bruder | last post by:
A week or two ago, I asked here about porting Python to C. Got some good answers (Note 1) but now I've got another question. Actually, more a request for clarification of a topic that both the Python tutorial and docs leave a touch murky to my understanding. Dictionaries/"dict" types... Am I understanding/interpreting correctly when I go...
2
4427
by: ben moretti | last post by:
hi i'm learning python, and one area i'd use it for is data management in scientific computing. in the case i've tried i want to reformat a data file from a normalised list to a matrix with some sorted columns. to do this at the moment i am using perl, which is very easy to do, and i want to see if python is as easy. so, the data i am...
1
2411
by: ±è»ó¿Ï | last post by:
I'm a newbie in Python and Python/C API.. I have a simple question. I want to access python dictionary data type from C extension module. ---- spam.c ---- #include <Python.h> PyObject *wrap_clear(PyObject *self, PyObject *args) { int count;
10
3672
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. Andrew dalke@dalkescientific.com
2
2715
by: quadric | last post by:
Hi, I would like to pass a dictionary from my Python code to my Python extension, extract various values from the dictionary (from within the extension) , modify the values for the relevant keys and return the modified dictionary to Python. Can someone point me to an example of what the C code might look like to do this?
14
3447
by: vatamane | last post by:
This has been bothering me for a while. Just want to find out if it just me or perhaps others have thought of this too: Why shouldn't the keyset of a dictionary be represented as a set instead of a list? I know that sets were introduced a lot later and lists/dictionaries were used instead but I think "the only correct way" now is for the...
10
1871
by: could.net | last post by:
Python dict is a hash table, isn't it? I know that hashtable has the concept of "bucket size" and "min bucket count" stuff, and they should be configurable so I can set them to the proper value when I know how many items I'm going to handle. If these two values can't be set, the hashtable will give them default values. When there are...
18
2952
by: Marko.Cain.23 | last post by:
Hi, I create a dictionary like this myDict = {} and I add entry like this: myDict = 1 but how can I empty the whole dictionary? Thank you.
7
3309
by: isinc | last post by:
I have an assignment that I'm working on and am having trouble. Not too familiar with graphics. Any help/guidance would be much appreciated to see if what I have so far is okay and what I should do for the loop part. I will post assignment details and what i have so far. You are given a dictionary named Stats, which is part of the template...
0
7807
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7730
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8058
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7820
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8100
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6456
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3742
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3753
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1344
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.