First, pickle
The pickle module is used to implement serialization and deserialization of Python objects. Pickle typically serializes a Python object into a binary stream or file.
Serialization and deserialization between Python objects and files:
Copy Code code as follows:
Pickle.dump ()
Pickle.load ()
If you want to implement serialization and deserialization between Python objects and strings, use:
Copy Code code as follows:
Pickle.dumps ()
Pickle.loads ()
The types that can be serialized are:
* None,true and False;
* Integers, floating-point numbers, complex numbers;
* String, byte stream, array of bytes;
* Contains tuples,lists,sets and dictionaries that can be pickle objects;
* Define functions at the top of the module:
* Built-in functions defined at the top of the module;
* Defines the class at the top of the module;
* Owning a custom type of __dict__ () or __setstate__ ();
Note: The serialization of a function or class is identified by name, so import of the corresponding module is required.
Second, the pickle of the operation process
In most cases, if the object picklable, we do not need additional code. By default pickle will intelligently examine the properties of classes and instances, and when a class instance is deserialized, its __init__ () method is usually not invoked. Instead, you first create an uninitialized instance and then revert to the stored property.
However, you can modify the default behavior by implementing the following methods:
Copy Code code as follows:
OBJECT.__GETSTATE__ (): The __dict__ of the object is serialized by default, but if you implement __getstate__ (), the value returned by the __getstate__ () function is serialized.
OBJECT.__SETSTATE__ (State): If the type implements this method, this method is used to recover the properties of the object when deserialized.
Object.__getnewargs__ (): This function needs to be implemented if the instance is constructed (__new__ ()) requires a parameter.
Note: if __getstate__ () returns false, __setstate__ () is not invoked at the time of deserialization.
Sometimes the __reduce__ () function needs to be implemented in order to be efficient, or if the 3 functions above do not meet the requirements.
Iii. examples
Copy Code code as follows:
Import Pickle
# an arbitrary collection of the objects supported by pickle.
data = {
' A ': [1, 2.0, 3, 4+6j],
' B ': ("character string", B "byte string"),
' C ': Set ([None, True, False])
}
With open (' Data.pickle ', ' WB ') as F:
# Pickle the ' data ' dictionary using the highest protocol available.
Pickle.dump (data, F, pickle.) Highest_protocol)
With open (' Data.pickle ', ' RB ') as F:
# The protocol version used is detected automatically
# have to specify it.
data = Pickle.load (f)
Print (str (data))
Modify the default behavior of the picklable type
Copy Code code as follows:
Class TextReader:
"" "Print and number lines in a text file." "
def __init__ (self, filename):
Self.filename = filename
Self.file = open (filename)
Self.lineno = 0
def readline (self):
Self.lineno = 1
& nbsp; line = Self.file.readline ()
if Not line:
return None
if Line.endswith (' \ n '):
line = line[:-1]
return '%i:%s '% (Self.lineno, line)
def __getstate__ (self):
# Copy The object ' s state from self.__dict__ which contains
# all our instance attributes. Always Use the dict.copy ()
# method to avoid modifying of the original state.
State = Self.__dict__.copy ()
# Remove the unpicklable entries.
Del state[' file ']
return state
def __setstate__ (self, State):
# Restore instance attributes (i.e., filename and Lineno).
Self.__dict__.update (state)
# Restore the previously opened file ' s state. To did so, we need to
# reopen it and read from it until the ' line ' count is restored.
File = open (Self.filename)
For _ in range (Self.lineno):
File.readline ()
# Finally, save the file.
Self.file = File
Reader = TextReader ("Hello.txt")
Print (Reader.readline ())
Print (Reader.readline ())
s = pickle.dumps (reader)
#print (s)
New_reader = Pickle.loads (s)
Print (New_reader.readline ())
# The output is
# 1:hello
# 2:how Are you
# 3:goodbye