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 isable to manipulate these data in a data file through maybe the pickle module? Withoutimporting your own class definition, will the data loaded from such a data file be usableor interpretable? please also explain with code its so URGENT
solution:
given data:
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()
please give me thumb up
Get Answers For Free
Most questions answered within 1 hours.