python--serializing objects using pickle

Source: Internet
Author: User
Tags object serialization serialization

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.