Serialization of the Python base module

Source: Internet
Author: User
Tags serialization

---What is serialization (picking)?

The process of changing a variable from memory to a storage or transfer is called serialization.

After serialization, the serialized content can be written to disk or transferred over the network to another machine.

In turn, re-reading the variable contents from the serialized object into memory is called deserialization, i.e. unpickling.

Example: Everyone should have played Warcraft, should know that the game has an archive function, I do not want to play at the time can be archived, and then play when we do not need to start playing again, just need to read the file on it. We are now learning about the object-oriented thinking, then in our eyes whether it is our game characters or game monsters, equipment, etc. can be regarded as a single object, for simple analysis.

Role objects (including attributes such as rank, gender, XP, HP, MP, and so on)
Weapon object (including the type of weapon, weapon damage, weapon additional capability value, etc.)
Monster objects (including level, XP, attack, Monster type, etc.)
So playing the game process is very interesting, creating a game character is like creating a character object, to get a weapon is like creating a weapon object, encounter monsters, NPCs and so on are objects.
And then with the knowledge of the analysis, we found that the object of data are stored in memory, we should all know that the memory of the data will disappear after the power outage, but our game after the archive, even if you shut down for a few days, and then into the game, read your archive found you in the game everything is still there, strange , obviously the memory of the data is gone, ah, this is why? So think carefully, the computer has a hard disk this thing after the power outage after the data is not lost (if due to power loss caused by the hard disk damage, no data, haha, not in this consideration). Then it should be easy to think that the data is saved on the hard drive. That's right! This is the persistence of objects, the serialization of the objects we are going to talk about today. Then deserialization is good to understand is to put the information stored in the hard disk and then read out to form an object.

How do---serialize?

Two modules are available in Python for serialization. Are pickle and JSON, respectively.

Pickle

Pickle is a unique serialization module in Python, so-called exclusive, which means that it cannot interact with the serialization of other programming languages because pickle converts the data object to bytes

>>> Import pickle>>> d=[1,2,3,4]>>> pickle.dumps (d) B ' \x80\x03]q\x00 (k\x01k\x02k\x03k\ x04e. ' >>> type (Pickle.dumps (d)) <class ' bytes ' >     #类型为bytes

The Pickle module provides four functions: dumps, dump, loads, load.

Both dumps and dump are serialized, while loads and load are deserialized.

dumps

Dumps serializes the value of the passed-in variable into a bytes, which can then be written to disk or transmitted.

While dump is more one step, you can pass in dump two parameters, one for the variable that needs to be serialized, and the other for the file that needs to be written.

Dump

Loads when we want to read the object from disk to memory, we can read the content to a bytes, and then deserialize the object with the loads method, or you can directly deserialize a file directly with the Load method.

loadsLoad

Json

If we are going to pass objects between different programming languages, we have to serialize the object into a standard format, such as XML, but the better way is to serialize it to JSON, because JSON represents a string that can be read by all languages, easily stored to disk, or transmitted over a network. JSON is not only a standard format, but also faster than XML, and can be read directly in the Web page, very convenient.

If you want to learn more about JSON, we recommend a blog post: http://www.cnblogs.com/mcgrady/archive/2013/06/08/3127781.html

The methods in JSON are similar to those in Pickle and dumps,dump,loads,load. There is no difference in usage, except that the serialized format is a character in JSON.

>>> Import json>>> d=[1,2,3,4]>>> json.dumps (d) ' [1, 2, 3, 4] ' >>> type (json.dumps (d )) <class ' str ' >           #类型为str

Because everything in Python is object, all objects are created based on classes, so ' class ' occupies a considerable proportion in Python. Can we serialize an instance of a class?

>>> class Student (object): ...     def __init__ (self,name,age,course): ...         self.name=name ...         self.age=age ...         Self.course=course ... >>> a=student (' Linghuchong ', ' Xixingdafa ') >>> import json>>> json.dumps (a) TypeError: <student object at 0x035b8230> was not JSON serializable

Dizzy, can't even! Now almost all object-oriented programming, class is so important, can not be serialized, how to do?

Don't worry, the previous code couldn't serialize the student class instance to JSON because by default, the dumps method doesn't know how to make the student instance a JSON ' {} ' object.

We need to ' tell ' how the JSON module is converted.

>>> def st_to_dict (a): ...     return {' name ': A.name, ' age ': a.age, ' Course ': a.course} ...     >>> Print (Json.dumps (a,default=st_to_dict))          #default参数就是告知json如何进行序列化 {"Course": "Xixingdafa", "name" : "Linghuchong", "Age": 24}    

Of course, if we were to define a class, it would be too much trouble to define an instance of this class to be converted to a dictionary function!! We have a way to do it once and for all.

Print (Json.dumps (A, Default=lambda obj:obj.__dict__))

The __dict__ does not need to be defined in the class, because the instance of class usually has a __dict__ attribute, which is a dictionary that stores instance variables.

>>> Print (a.__dict__) {' Course ': ' Xixingdafa ', ' age ': $, ' name ': ' Linghuchong '}

Serialization of the Python base module

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.