[Tutor] class data

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 2 Dec 2001 20:26:28 -0800 (PST)


On Sun, 2 Dec 2001 fleet@teachout.org wrote:

> On Sun, 2 Dec 2001, Danny Yoo wrote:
> > > So if class data is not stored in standard containers, where is it
> > > stored (and how)?  (I'm talking about the names, phone numbers, e-mail
> > > addresses, etc. in the AddrBookEntry class example.)
> >
> > >From what I remember, instance data actually is stored in a standard
> > dictionary container:
> >
> > ###
> > >>> a = AddrBookEntry('John Doe', '405-555-1212')
> > Created instance for: John Doe
> > >>> a.__dict__
> > {'phone': '405-555-1212', 'name': 'John Doe'}
> > ###
> >
> > Python usually hides this dictionary so that, in casual use, we never
> > really need to worry about it --- we can just access the 'properties' of
> > our class with the special Python notation:
> >
> 
> I load the module, add a name and phone number, exit python, turn off the
> computer, come back in two days, turn on computer, load the module.  Data
> is gone.
> 
> Do I (or should I) use a dictionary to store the data?  Long term.  And if
> I do need to use the dictionary, what advantage do I gain by funneling
> everything through a class structure?


Ah!  Take a look at the 'pickle' module:

    http://python.org/doc/lib/module-pickle.html

'pickle' knows how to deal with instances, and will properly allow you to
save data structures as a byte stream.

It doesn't work on pathological cases (like C extension modules or files),
at least, not without a bit of hacking with the 'copy_reg' module.  

Try it out, and if you have problems with it, please email the list, and
we can ferment an example.