Encapsulation is the process of converting a Python data object into a stream of bytes, and unpacking is the inverse of the package, converting bytes in a byte file or byte object into a Python data object, and not unpacking the data from the untrusted data source. Almost any Python data object can be encapsulated and unpacked, mainly including:
None, True,false
integers, floating-point numbers, complex numbers
String, Byte, ByteArray object
Tuples, lists, collections, dictionaries containing encapsulated objects
Functions defined at the top level of a module
Built-in functions defined at the top level of a module
That is the class defined on the top level of a module
The result of __dict__ or calling __getstate__ () is an instance of the encapsulated class
The methods commonly used in pickle modules are:
1. Pickle.dump (obj, file, Protocol=none,)
Required parameter obj represents the object that will be encapsulated
The required parameter file represents the object to which obj is to be written, which must be opened in binary writable mode, the "WB"
Optional parameter protocol indicates the protocol that is used to inform Pickler, the supported protocols are 0,1,2,3, the default protocol is to add protocol 3 in Python 3, and the other protocol details are referenced in the documentation
2. Pickle.load (File,*,fix_imports=true, encoding= "ASCII", errors= "strict")
Required parameter file must be opened in binary readable mode, "RB", other optional parameters
3. Pickle.dumps (OBJ): Returns encapsulated object as a byte object without writing to the file
4. Pickle.loads (Bytes_object): reads the encapsulated object from the byte object and returns
There are three types of exceptions that can occur with the Pickle module:
1. Pickleerror: Exception classes that occur when encapsulating and unpacking, inherited from exception
2. Picklingerror: Exception that occurs when a non-encapsulated object is encountered, inherited from Pickleerror
3. Unpicklingerror: An exception occurred during the unpacking of the object, inherited from Pickleerror
Pickle Application Examples:
Copy the Code code as follows:
Import Pickle
With open ("My_profile.txt", "WB") as Myprofile:
Pickle.dump ({"Name": "Alwaysjane", "Age": "20+", "Sex": "Female"}, Myprofile)
With open ("My_profile.txt", "RB") as Get_myprofile:
Print (Pickle.load (get_myprofile))
Copy the Code code as follows:
Import Pickle
Class Profile:
Name = "Alwaysjane"
Pickledclass = pickle.dumps (Profile)
Print (Pickledclass)
Print (Pickle.loads (pickledclass))
Understanding is not very thorough, hope that the great God to correct wrong ...
Attached Reference Document