Advertisement
wagner-cipriano

Serializing objects in python using pickle module

Jul 24th, 2018
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul 24 17:37:49 2018
  4. @author: Wagner Cipriano
  5. REF: https://docs.python.org/2/library/pickle.html
  6.  Using pickle module to serialize objects in python
  7.  The pickle module can transform a complex object into a byte stream and it can transform the byte stream into an object with the same internal structure
  8.  
  9. """
  10. import pickle
  11.  
  12. class Address:
  13.     def __init__(self, line1, line2, city):
  14.         """ constructor """
  15.         self.Line1 = line1
  16.         self.Line2 = line2
  17.         self.City = city
  18.  
  19.     def __str__(self, ):
  20.         """ str function """
  21.         return '%s. %s, City: %s ' %(self.Line1, self.Line2, self.City)
  22.  
  23.  
  24. class Person:
  25.     def __init__(self, idperson, name, age, height, weight):
  26.         """ constructor """
  27.         self.IdPerson = idperson
  28.         self.Name = name
  29.         self.Age = age
  30.         self.Height = height
  31.         self.Weight = weight
  32.         self.address = []
  33.  
  34.     def __str__(self, ):
  35.         """ str function """
  36.         s = """%s - %s\n  Age:     %s\n  Height:  %s\n  Weight:  %s""" \
  37.         %(self.IdPerson, self.Name, self.Age, self.Height, self.Weight)
  38.         for addr in self.address:
  39.             s += '\n  Address: %s' %(addr)
  40.         return s
  41.  
  42.     def add_address(self, line1, line2, city):
  43.         """ address """
  44.         addr = Address(line1, line2, city)
  45.         self.address.append(addr)
  46.  
  47. #create class instance
  48. Me = Person(1, 'Wagner', 21, 1.90, 92.50)
  49. Me.add_address(line1='39 East', line2='79th st.', city='New York')
  50.  
  51. #serialize Person class instance (Me)
  52. with open('filename.pkl', 'wb') as File:
  53.     pickle.dump(Me, File, protocol=pickle.HIGHEST_PROTOCOL)
  54.  
  55. #load serialized class from file
  56. with open('filename.pkl', 'rb') as File:
  57.     #print File.Read()
  58.     Me_reloaded_from_fs = pickle.load(File)
  59.  
  60. print 'Me_reloaded_from_fs:\n', str(Me_reloaded_from_fs)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement