sharing dictionaries amongst class instances

Kerry Neilson kmneilso at REMOVEyahoo.com
Sun Nov 9 17:07:18 EST 2003



Kerry,

two observations:

1) That's not proper Python! ;-) and 2) I think the behaviours you want are
only available in 'new style' classes, i.e. classes based upon 'object'. Did
you mean:

---8<---
class A(object):
  my_dict = []
  dict_entry = { 'key1':0, 'key2':0 }

  def __init__(self):
    for x in range(10):
          tmp = copy.deepcopy(self.dict_entry)
          tmp['key1'] = x
          self.my_dict.append(tmp)
---8<---

A.my_dict is a /class variable/, i.e. it is tied to the class, not the
instance - there's only one of them, viz:

---8<---
>>> inst0,inst1=A(),A()
>>> id(inst0),id(inst1) # get the id of the instances:
(1083256236, 1083254732)
>>> id(inst0.my_dict),id(inst1.my_dict) # and the id of their my_dict lists:
(1083253228, 1083253228)
>>> inst0.my_dict is inst1.my_dict
True
>>>
---8<---

If you move the initial assignment of my_dict into the __init__() procedure,
and call it self.my_dict() instead, then you'll get a new instance of a list
each time - maybe this is what you want.  BTW, is there any particular
reason
for choosing the word 'my_dict' to describe a list?

hope this helps you arrive at a solution ;-)



Thanks for the reply, Andy.
Your observation was correct, as I also learned from Peter, and moving the
initial assignment into __init__ is whta I wanted.  I guess I didn't realize
that one could do that, being more familiar with c++.  And no, calling a
list my_dict was pure accident.  Perhaps my explanation in response to Peter
explains it a bit better.

Thanks.






More information about the Python-list mailing list