Python Pickle - Custom Class Object
Python Pickle - Custom Class Object
You can pickle a custom python class object and then unpickle it using pickle.dump() and pickle.load().
In this tutorial, we shall go through example programs to learn how to pickle a python class object.
1. Pickle a custom class object
In the following example, we have defined a class called Laptop and created an object for it. Then we shall pickle it to a file called laptop1.
Python Program
import pickle
class Laptop:
def __init__(self, name, processor, hdd, ram, cost):
self.name = name
self.processor = processor
self.hdd = hdd
self.ram = ram
self.cost = cost
def details(self):
print('The details of the laptop are:')
print('Name :', self.name)
print('Processor :', self.processor)
print('HDD Capacity :', self.hdd)
print('RAM :', self.ram)
print('Cost($) :', self.cost)
#create object
laptop1 = Laptop('Dell Alienware', 'Intel Core i7', 512, 8, 2500.00)
#create a pickle file
picklefile = open('laptop1', 'wb')
#pickle the dictionary and write it to file
pickle.dump(laptop1, picklefile)
#close the file
picklefile.close()
A file called laptop1 would be created in the current working directory.
2. Un-pickle a custom class object
In the following example, we will unpickle the file that is created in the above example. Then call a method of the class object. Note that either the class has to be at top level in the module or has to be defined here as well.
Python Program
import pickle
class Laptop:
def __init__(self, name, processor, hdd, ram, cost):
self.name = name
self.processor = processor
self.hdd = hdd
self.ram = ram
self.cost = cost
def details(self):
print('The details of the laptop are:')
print('Name :', self.name)
print('Processor :', self.processor)
print('HDD Capacity :', self.hdd)
print('RAM :', self.ram)
print('Cost($) :', self.cost)
#read the pickle file
picklefile = open('laptop1', 'rb')
#unpickle the dataframe
laptop1 = pickle.load(picklefile)
#close file
picklefile.close()
#print the dataframe
print(type(laptop1))
laptop1.details()
Output
<class '__main__.Laptop'>
The details of the laptop are:
Name : Dell Alienware
Processor : Intel Core i7
HDD Capacity : 512
RAM : 8
Cost($) : 2500.0
Summary
In this tutorial of Python Examples, we learned how to serialize and de-serialize a Python custom class object.