sharing dictionaries amongst class instances

Andy Jewell andy at wild-flower.co.uk
Sun Nov 9 16:45:00 EST 2003


On Sunday 09 Nov 2003 8:22 pm, Kerry Neilson wrote:
> Hi,
> Really hung up on this one.  I'm trying to get all the fields of a
> dictionary to be unique for each class:
>
> class A {
>   my_dict = []
>   dict_entry = { 'key1':0, 'key2':0 }
>
>   __init__(self):
>     for x in range(10):
>           tmp = copy.deepcopy(self.dict_entry)
>           tmp['key1'] = x
>           self.my_dict.append(tmp)
> }
>
> in a driver, I have
>
> inst0, inst1 = A.A(), A.A()
> inst0.my_dict[1]['key2'] = "ted"
> inst1.my_dict[5]['key2'] = "steve"
> inst0.display()
> inst1.display()
>
> printing them out shows that both objects have ted and steve in their
> dictionaries.  I have done this very thing outside of a class, and it works
> wonderfully.  All other attributes in the class are able to remain unique.
> ie, inst0.data = 5 and inst1.data = 8 works fine.
> I believe I could set the dictionaries up beforehand, but they will be
> substatially different sizes, and it certainly wouldn't be proper.
>
> Any ideas?  Thanks very much for any insight.

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 ;-)

-andyj






More information about the Python-list mailing list