Python Learning Note __9.4 serialization

Source: Internet
Author: User
Tags object serialization serialization

# This is a learning note for the Liaoche teacher Python tutorial

1 , overview

All variables are in memory during the program's run. But once the program is finished, the memory used by the variables is fully recycled by the operating system. And if you want to save changes to the variables, we can serialize them.

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

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.

2 , Pickle Module

Python provides the pickle module for serialization and deserialization

1. Serialization

d = dict (name= ' Bob ', age=20, score=88) # Define a dictionary

# p ickle.dumps () --object serialization bytes and print it out, you need to write the file manually

>>> Import Pickle # import pickle module

>>> Pickle.dumps (d) # Serializes the object into a bytes

B ' \x80\x03}q\x00 (x\x03\x00\x00\x00ageq\x01k\x14x\x05\x00\x00\x00scoreq\x02kxx\x04\x00\x00\x00nameq\x03x\x03\ X00\x00\x00bobq\x04u. '

# pickle.dump () --Write the serialized information directly file-like Object , do not print

>>> f = open (' Dump.txt ', ' WB ') # Create file Object

>>> Pickle.dump (d, F) # serialize D , binary format write f

>>> f.close () # close File Objects

2. Deserialization

# pickle.loads ()--deserialization based on generated bytes

x=b ' \x80\x03}q\x00 (x\x03\x00\x00\x00ageq\x01k\x14x\x05\x00\x00\x00scoreq\x02kxx\x04\x00\x00\x00nameq\x03x\x03 \x00\x00\x00bobq\x04u. ' # Assign the serialized bytes to x

>>> pickle.loads (x) # anti-serialization

{' Age ': ' Score ': ' The ' name ': ' Bob '}

# pickle.load ()--read file-like Object of Data deserialization

>>> f = open (' Dump.txt ', ' RB ') # Create a readable file object. Format is binary

>>> d = pickle.load (f) # read Data from F , deserialize

>>> F.close ()

>>> D

{' Age ': ' Score ': ' The ' name ': ' Bob '}

3. Attention

The deserialized variables and the original variables are completely irrelevant objects, they are just the same content .

Pickle can only be used with Python, and it is possible that different versions of Python are incompatible with each other, so you can only use pickle to save unimportant data

3 , JSON the serialization

If you want to pass objects between different programming languages, you must serialize the objects into a standard format. JSON, in other words, is a string that can be read by all languages, easily stored to disk, or transmitted over a network.

The Python object-to-JSON conversion requires a JSON module that invokes a method similar to the Pickle module.

D = dict (name= ' Bob ', age=20, score=88)

1. Serialization

# json.dumps () --Serialize and print

>>> Import JSON

>>> Json.dumps (d)

' {' Age ': "Score": "," "Name": "Bob"} '

# Json.dump --write JSON directly to a file-like Object

2. Deserialization

# json.loads () --Put J string deserialization of son

>>> json_str = ' {' Age ': "Score": "," "Name": "Bob"} '

>>> json.loads (JSON_STR)

{' Age ': ' Score ': ' The ' name ': ' Bob '}

# json.load () --Reads the string from the File-like object and deserializes it

3 , class serialized to JSON

1. Serialization

Import JSON

Class Student (object):

def __init__ (self, name, age, score):

Self.name = Name

Self.age = Age

Self.score = Score

s = Student (' Bob ', 20, 88)

Print (Json.dumps (s))

If we serialize the instance of student directly to JSON, an error will be given. This is because by default, the dumps () method does not know how to change an instance of student into a JSON {} object.

the optional parameter, default, can turn any object into a can be serialized as JSON object, we just need to write a conversion function for student, and then pass the function in.

def student2dict (STD):

return {

' Name ': Std.name,

' Age ': Std.age,

' Score ': Std.score

}

The student instance is first converted to a DICT object that can be serialized as json by the student2dict () function, which is then successfully serialized into JSON

>>> Print (Json.dumps (s, default=student2dict))

{"Age": +, "name": "Bob", "Score": 88}

Writing specialized function serialization is too cumbersome. A more concise approach is as follows:

# turn an instance of any class into Dict

# The instance s, passed to the obj parameter, and returned obj.__dict__ is a dict

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

Typically an instance of class has a __dict__ attribute, which is a dict that stores instance variables

>>> s.__dict__

{' name ': ' Bob ', ' age ': $, ' score ': 88}

>>> type (s.__dict__)

<class ' Dict ' >

2. Deserialization

The loads () method first converts a Dict object, and then the object_hook function We pass in is responsible for converting dict to student instances

# Dict conversion to student () function

def dict2student (d):

return Student (d[' name '], d[' age '), d[' score '])

>>> json_str = ' { "Age": "Score": "," "Name": "Bob"} '   # need to deserialize Span style= "font-family: Microsoft JAS Black; color: #00B050" >json string

>>> Print (Json.loads (json_str, object_hook=dict2student)) will be Json_str by Dict2student translates to Student ()

<__main__. Student Object at 0x10cd3c190>


Python Learning Note __9.4 serialization

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.