sharing dictionaries amongst class instances

Peter Otten __peter__ at web.de
Sun Nov 9 16:23:15 EST 2003


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

class A { ... } is *not* Python. Are you converting from Java :-) ?
>From what follows, I conclude that you want the dicitonary to be unique for
each *instance* (if you want it unique for the class, you are already
there). Unlike Java, you must put it in the constructor then (untested):

class A:
    def __init__(self):
        self.my_dict = {"key1": 0, "key2": 0}

Dictionaries are the {} thingies, [] indicate list literals. Deepcopy should
be buried very deep in the documentation, where no newbie will ever find
it...
Seriously, take the time to read the excellent tutorial that comes with
Python, and only then try to clean up this mess.

Peter







More information about the Python-list mailing list