Pickle performing class instantiation ??

Peter Otten __peter__ at web.de
Tue Feb 28 17:14:36 CET 2012


Smiley 4321 wrote:

> Am I doing the right thing for -
> 
> - Have a class
> - Instantiate the class with 3 parameters
> - pickle the class instance
> - generate a bytestream (.pkl) using pickle.dump, simply guessing -
> 
> as -
> 
> ---
> #!/usr/bin/python
> 
> import pickle
> 
> class Pickle:
>     def __init__(self, Parameter1, Parameter2, Parameter3):
>         self.PM1 = Parameter1
>         self.PM2 = Parameter2
>         self.PM3 = Parameter3

# You need something to pickle first.
# You could call it "self", but that is confusing
# as this name is by convention used inside methods as
# the current instance. So:
p = Pickle(1, 2, 3)

> with open('/tmp/readfile.pkl', 'wb') as f:
      # Don't touch the object's attributes, 
      # pickle the whole instance instead:
      pickle.dump(p, f)

> with open('/tmp/readfile.pkl', 'rb') as f:
      # Load the instance back from file
      p = pickle.load(f)

# print it 
print p.PM1
print p.PM2
print p.PM3





More information about the Python-list mailing list