[Tutor] unpickling a class

Timothy Wilson wilson@visi.com
Fri, 21 Dec 2001 16:49:41 -0600 (CST)


On Sat, 22 Dec 2001, Andy W wrote:

> > I'm having trouble building a constructor method for the Portfolio class
> > that allows me to *either* create a portfolio instance from scratch or
> > load one from disk using the pickle module.
> 
> How about something like:
> 
> import pickle
> 
> class Portfolio:
>   def __init__(self,pickle_file=None):
>     if pickle_file is not None:
>       pickled_instance=pickle.load(pickle_file)
>       ... extract whatever you need from it
>     else:
>       ... continue as normal

OK, this make sense. I'm puzzled about the "... extract whatever you
need from it" part. It doesn't seem as though the attributes that have
been pickled are automatically unpickled. 

Here's my constructor method:

class Portfolio:
    def __init__(self, file=None):
        if file is not None:
            if fileExists(file):
                f = open(file, 'r')
                self = pickle.load(f)
                self.filename = file
                self.modified = 0
            else:
                print "File '%s' does not exist." % file               
        else:   
            self.owner = raw_input("Your name: ")
            self.account= raw_input("Account # ")
            self.contents = []
            self.modified = 0
            self.filename = ''

It would be nice if the 'self = pickle.load(f)' would automatically
regenerate all the instance's attributes. I looked in the file and I
know that "owner" and "account" attributes were there.

Any pointers?

-Tim

--
Tim Wilson      |   Visit Sibley online:   | Check out:
Henry Sibley HS |  http://www.isd197.org   | http://www.zope.com
W. St. Paul, MN |                          | http://slashdot.org
wilson@visi.com |  <dtml-var pithy_quote>  | http://linux.com