In: Computer Science
In python, why is it advantageous to store not just data (as vectors, arrays,etc.) but perhaps the object (an instance of your user-defined class) that contains and is able to manipulate these data in a data file through maybe the pickle module? Without importing your own class definition, will the data load from such a data file be usable or interpretable? Explain and write some codes to support your ideas if possible.
By storing the object intance, you are able to store the complete current state of the object along with the data. So when you need to re-create the object, you can easily do without manual data parsing.
You need to import the class definition, in order to manipulate data. Otherwise, data manipulation on the object will not work, because pickle only stores the state of the object, not the class definition.
The two python files demo this process. On file has the class definition saves an object to a file. The other file mporta the class defintion and it reads the data from the file, and invokes a function of the object.
Program Screenshots for Indentation Reference:
Sample Output:
Program code to copy:
picklerDemo.py:
from pickle import Pickler
# custom class for demo
class Person:
def __init__(self, name):
self.name = name
def printName(self):
""" Function to print
the name"""
print(self.name)
#create an object and save object to file
obj = Person("John Doe")
with open("john.pickle", "wb") as f:
Pickler(f).dump(obj)
unpickleDemo.py:
from pickleSaver import Person
from pickle import Unpickler
with open("john.pickle", "rb") as f:
obj = Unpickler(f).load()
# invoke method of the object
obj.printName()