Encapsulation is a process of converting a Python data object into a byte stream. unblocking is an encapsulation inverse operation that converts byte files or byte objects into Python data objects, do not unseal data from trusted data sources. It can encapsulate and unseal almost any Python data objects, including:
None, True, False
Integer, floating point, plural
String, byte, ByteArray object
Tuples, lists, and sets, including dictionaries of encapsulated objects
Function defined at the top layer of a module
Built-in functions defined at the top layer of a module
It is a class defined at the top layer of a module.
The result of _ dict _ or call _ getstate _ () is an instance of an encapsulated class.
Common pickle modules include:
1. pickle. dump (obj, file, protocol = None ,)
Required parameter obj indicates the object to be encapsulated
The required parameter file indicates the object to be written to by obj. The file must be opened in binary writable mode, that is, "wb"
The optional parameter protocol indicates the protocol used by pickler. The supported protocols are 0, 1, 2, and 3. The default protocol is protocol 3 added to Python 3. For details about other protocols, see the reference document.
2. pickle. load (file, *, fix_imports = True, encoding = "ASCII", errors = "strict ")
The required parameter file must be opened in binary readable mode, that is, "rb". Other parameters are optional.
3. pickle. dumps (obj): return the encapsulated object in the form of a Byte object without writing it into the file.
4. pickle. loads (bytes_object): Read the encapsulated object from the Byte object and return
Three exceptions may occur in the pickle module:
1. PickleError: The Exception class during encapsulation and unpacking. It inherits from Exception.
2. PicklingError: the exception that occurs when an unencapsulated object is encountered. It is inherited from the PickleError
3. UnPicklingError: An exception occurred during object unpacking. It is inherited from PickleError.
Pickle application instance:
Copy codeThe Code is 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 codeThe Code is as follows:
Import pickle
Class Profile:
Name = "AlwaysJane"
Pickledclass = pickle. dumps (Profile)
Print (pickledclass)
Print (pickle. loads (pickledclass ))
Understanding is not very thorough. I hope you can correct the mistakes...
Attached references