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 object and write it to file
pickle.dump(laptop1, picklefile)
#close the file
picklefile.close()
Explanation:
- The
Laptop
class is defined with attributes such asname
,processor
,hdd
,ram
, andcost
, along with a methoddetails()
to print the laptop details. - An object of the
Laptop
class,laptop1
, is created with sample values. - A file
laptop1
is opened in write-binary mode (wb
) usingopen()
. - The
pickle.dump()
function is called to serialize the object and write it to the file. - The file is then closed to finalize the pickling process.
A file called laptop1 would be created in the current working directory containing the pickled object.
2. Un-pickle a Custom Class Object
In the following example, we will unpickle the file created in the above example. We will then call the details()
method of the class object. Note that either the class definition must be at the top level of the module, or it must be defined here as well for successful unpickling.
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 object
laptop1 = pickle.load(picklefile)
# Close file
picklefile.close()
# Print the object type and call the details method
print(type(laptop1))
laptop1.details()
Explanation:
- The
Laptop
class is redefined in the same way to ensure it is available during unpickling. - The file
laptop1
is opened in read-binary mode (rb
) usingopen()
. - The
pickle.load()
function is called to deserialize the object, re-creating the originalLaptop
object. - The
type()
function is used to verify that the object is of typeLaptop
, and then thedetails()
method is called to display the laptop information.
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
3. Pickle Multiple Class Objects
In some cases, you may need to pickle and unpickle multiple objects at once. Here is an example where we pickle a list of Laptop
objects:
Python Program
# Create multiple laptop objects
laptop2 = Laptop('HP Omen', 'Intel Core i9', 512, 16, 3000.00)
laptop3 = Laptop('Apple MacBook Pro', 'M1 Chip', 256, 16, 2400.00)
# List of laptops
laptops = [laptop1, laptop2, laptop3]
# Pickle the list of laptop objects
picklefile = open('laptops_list', 'wb')
pickle.dump(laptops, picklefile)
picklefile.close()
# Unpickle the list
picklefile = open('laptops_list', 'rb')
laptops_list = pickle.load(picklefile)
picklefile.close()
# Print details of all laptops
for laptop in laptops_list:
laptop.details()
Explanation:
- We create multiple objects (
laptop2
andlaptop3
) of theLaptop
class. - These objects are stored in a list
laptops
. - The list is then pickled into a file called
laptops_list
. - We unpickle the list, retrieving all laptop objects, and call the
details()
method for each object to display the laptop information.
Summary
In this tutorial, we learned how to serialize and deserialize custom class objects using the Pickle library. We explored how to pickle and unpickle a single class object, as well as how to handle multiple class objects at once. These techniques are essential for saving and restoring custom objects in Python.