sharing dictionaries amongst class instances

Kerry Neilson kmneilso at REMOVEyahoo.com
Sun Nov 9 23:02:18 CET 2003


> 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.


hmm ... I didnt' word this quite right.  I want a list [] of dictionaries
{}.  I mean for it to be similar to an array of structs in C, only using a
dictionary instead of a struct and a list instead of an array.  Seem
reasonable?

I have read the entire tutorial as well as "Learning Python" in its utter
entirety.  This is precisely how I know of deepcopy.  I noticed that when I
appended dictionaries to my list, modifying one modifed them all.  I want
each entry to be unique.  I don't see how to do this without deepcopy.  What
really confuses me is that this same scenario works when not embedded in a
class.

As for your suggestion, putting the dictionary initialization and the list
in the contructor did the trick.  I had this:

class a:
  x = 0
  y = 0
:

I suppose it's a c++ leftover thing, thinking i had to declare before I
init.  I don't yet understand why it's different for a simple data type than
it is for the list of dictionaries.  But by taking the dict_entry{} and
my_dict[] out of the top of the class, it works without deepcopy.    Thanks
for the help.






More information about the Python-list mailing list