Pickle Serialized Objects
If you want to store Python objects transparently without losing information such as their identity and type, you need some form of object serialization: It is a process of turning arbitrarily complex objects into text or binary representations of objects.
Similarly, you must be able to restore an object to its original object in a serialized form. In Python, this serialization process is called Pickle,
You can pickle an object into a string, a file on disk, or any file-like object, or you can unpickle the string, file, or any file-like object into the original object
Code instance
Import Pickleclass Mypickle (object): Def __init__ (self,file_name): self.file_name = file_name def dump (self,o BJ): "" "serialized object:p Aram obj:: return:" "with open (self.file_name, ' AB ') as F: Pickle.dump (obj, f) print (' Dump data ', obj.__dict__) def loaditer (self): "" "iterates over the deserialized object : Return: "" "F = open (Self.file_name, ' RB ') while True:try:obj = Pickle.load (f) yield obj except Eoferror:print (' Eoferror ') f.clo SE () print (f.closed) breakclass person:def __init__ (self,n,a): self.name=n Self.age=a def Show (self): print (self.name+ "_" +str (self.age)) AA = person ("Agood", 2) BB = person ("Bgood", 3) cc = Person ("Cgood", 4) p = mypickle (' c.txt ') p.dump (aa) P.dump (BB) p.dump (cc) iter_obj = P.loaditer () while True:try:pri NT (Next (iter_obj). __dict__) except Stopiteration:print (' Stop ') break
Output results
Dump data {' name ': ' Agood ', ' age ': 2}dump data {' name ': ' Bgood ', ' age ': 3}dump data {' name ': ' Cgood ', ' age ': 4}{' name ': ' A Good ', ' age ': 2}{' name ': ' Bgood ', ' age ': 3}{' name ': ' Cgood ', ' age ': 4}eoferrortruestop
python--serializing objects using pickle