Pickle: several class instance objects in one file?

G

Guest

Hi everyone

I've never used the module 'pickle' so far, thus I've got some questions about how to use it:

Lets say I have instances of class A and class B:

a = A()
b = B()

Is it possible to pickle both of these instances to the same pkl-file or will that have any bad impact for unpickle (i.e. the instance are 'mixed' or 'destroyed')? Or should I rather use a seperate file for every class instance I want to pickle?

Another very basic question about pickling class instances:

To store the value of attributes of an instance is it enough for the pickling-algorithm to use the __dict__ or do I have to implement the _setstate_ and _getstate_ function? I didn't really get the meaning of those while reading the python user manual...

Thanks in advance

Dominique
 
M

Marc 'BlackJack' Rintsch

Lets say I have instances of class A and class B:

a = A()
b = B()

Is it possible to pickle both of these instances to the same pkl-file or
will that have any bad impact for unpickle (i.e. the instance are
'mixed' or 'destroyed')? Or should I rather use a seperate file for
every class instance I want to pickle?

You can pickle a data structure, for example a tuple, that contains both
instances.

Or you can write one after the other into the pickle file. Then you'll
have to retrieve them in two steps too.
Another very basic question about pickling class instances:

To store the value of attributes of an instance is it enough for the
pickling-algorithm to use the __dict__ or do I have to implement the
_setstate_ and _getstate_ function? I didn't really get the meaning of
those while reading the python user manual...

Usually `pickle` just works. Those methods can be used if you want to
customize the process, for example if you don't want to pickle the entire
object but just parts of it.

Ciao,
Marc 'BlackJack' Rintsch
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top