Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Created on Tue Jul 24 17:37:49 2018
- @author: Wagner Cipriano
- REF: https://docs.python.org/2/library/pickle.html
- Using pickle module to serialize objects in python
- 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
- """
- import pickle
- class Address:
- def __init__(self, line1, line2, city):
- """ constructor """
- self.Line1 = line1
- self.Line2 = line2
- self.City = city
- def __str__(self, ):
- """ str function """
- return '%s. %s, City: %s ' %(self.Line1, self.Line2, self.City)
- class Person:
- def __init__(self, idperson, name, age, height, weight):
- """ constructor """
- self.IdPerson = idperson
- self.Name = name
- self.Age = age
- self.Height = height
- self.Weight = weight
- self.address = []
- def __str__(self, ):
- """ str function """
- s = """%s - %s\n Age: %s\n Height: %s\n Weight: %s""" \
- %(self.IdPerson, self.Name, self.Age, self.Height, self.Weight)
- for addr in self.address:
- s += '\n Address: %s' %(addr)
- return s
- def add_address(self, line1, line2, city):
- """ address """
- addr = Address(line1, line2, city)
- self.address.append(addr)
- #create class instance
- Me = Person(1, 'Wagner', 21, 1.90, 92.50)
- Me.add_address(line1='39 East', line2='79th st.', city='New York')
- #serialize Person class instance (Me)
- with open('filename.pkl', 'wb') as File:
- pickle.dump(Me, File, protocol=pickle.HIGHEST_PROTOCOL)
- #load serialized class from file
- with open('filename.pkl', 'rb') as File:
- #print File.Read()
- Me_reloaded_from_fs = pickle.load(File)
- print 'Me_reloaded_from_fs:\n', str(Me_reloaded_from_fs)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement