In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to understand Python object serialization and deserialization", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "how to understand Python object serialization and deserialization"!
Catalogue
Introduction
Pickle
Json
The last words
Introduction
The process of converting the state information of an object into a form that can be stored or transmitted is called serialization
Similar conversion from serialized data to corresponding objects is called deserialization
This article introduces two modules of serialization and deserialization of objects in Python.
Picklejson
Pickle
Pickle# serialization In [19]: num = 66In [20]: s = 'python'In [21]: pi = 3.14In [22]: li = [1,2 3] In [27]: b_num = pickle.dumps (num) In [28]: b_pi = pickle.dumps (s) In [29]: b_pi = pickle.dumps (pi) In [30]: b_li = pickle.dumps (li) In [31]: b_numOut [31]: B'\ x80\ x03KB.'In [32]: b_sOut [32]: B'\ x80\ x03X\ X06\ X00\ x00pythonq\ x00.'In [33]: [33]: B'\ x80\ x03G@\ t\ x1e\ xb8Q\ xeb\ x85\ x1f.'In [34]: b_liOut [34]: B'\ x80\ x03] Q\ x00 (K\ x01K\ x02K\ x03e.' In [35]: type (b_li) Out [35]: bytes # deserialization In [47]: pickle.loads (b_num) Out [47]: 66In [48]: pickle.loads (baths) Out [48]: 'python'In [49]: pickle.loads (b_pi) Out [49]: 3.14In [50]: li = pickle.loads (b_li) In [51]: liOut [51]: [1,2] 3] In [52]: type (li) Out [52]: list
Custom objects can also be serialized
Class User: def _ _ init__ (self, name, sex): self.name = name self.sex = sex In [38]: user = User ('hui' 'male') In [39]: b_user = pickle.dumps (user) In [40]: b_userOut [40]: B'\ x80\ x03cm mainstay _\ nUser\ nq\ X00)\ x81q\ X01} Q\ X02 (X\ X04\ X00\ X00\ x00nameq\ x03X\ X03\ X00\ X00\ x00sexq\ x05X\ X03\ X00\ X00\ xe7\ x94\ xb7q\ x06ub.'In [41]: type (b_user) Out [41]: bytesIn [42]: user = pickle.loads (b_user) In [43]: type (user) Out [43]: _ main__.UserIn [44]: user.nameOut [44]: 'hui'In [45]: user.sexOut [45]:' male'
Note: after pickle serialization, the data is of bytes type.
Pickle can also serialize objects to a file and then deserialize them back from the file.
Import pickleclass User: def _ init__ (self, name, sex): self.name = name self.sex = sex user = User ('ithui',' male') f = open ('user.txt', mode='wb') pickle.dump (user, f) f.close ()
Reverse the object from the file
In [3]: F = open ('user.txt',' rb')...: user = pickle.load (f)...: f.close (): In [4]: userOut [4]: In [5]: user.nameOut [5]: 'ithui'In [6]: user.sexOut [6]:' male'
Although the pickle module can serialize objects, it is only suitable for the Python language, so it is not convenient for data exchange. For example, if you send the data to the front end, js will not be able to convert the data to what you want.
Json
If we want to pass objects between different programming languages, we must serialize the objects to a standard format, such as json, because the json representation is a string that can be read by all languages, or can be easily stored to disk or transferred over the network for data exchange.
The object represented by the json string is the object of js. The built-in data types of json and Python are as follows:
JSON type Python type {} dict [] list "string" 'str' or u'unicode'3.14int or floattrue / falseTrue / FalsenullNoneIn [7]: import jsonIn [8]: info_dict = {.:' name': 'hui',.:' age': 22,.: 'is_admin': True,.:' hobbies': ['play chess', 'write code'] ...: 'other': None...:} In [9]: info_json = json.dumps (info_dict) In [10]: info_jsonOut [10]:' {"name": "hui", "age": 22, "is_admin": true, "hobbies": ["\ u4e0b\\ u8c61\\ u68cb" "\\ u5199\\ u4ee3\\ u7801"], "other": null}'# deserialized In [16]: info_d = json.loads (info_json) In [17]: info_dOut [17]: {'name':' hui', 'age': 22,' is_admin': True, 'hobbies': [' chess', 'code'] 'other': None} In [18]: type (info_d) Out [18]: dict
See if custom class objects can be serialized by json
In [21]: import jsonIn [22]: class User:...: def _ init__ (self, name, sex):...: self.name = name...: self.sex = sex...: In [23]: user = User ('ithui',' male') In [24]: json.dumps (user) TypeError: Object of type User is not JSON serializable
An error was reported that the User object could not be serialized by json. Is there any way to convert custom objects to json? there must be.
The general idea is to convert the User object into an object that can be serialized by json, such as dict, and then give the serializable object to the json module.
In [28]: def user2dict (obj):...: return {'name': obj.name,' sex': obj.sex}...:: In [29]: user = User ('ithui',' male') In [30]: user_dict = user2dict (user) In [31]: user_dictOut [31]: {'name':' ithui' 'sex':' male'} In [32]: user_json = json.dumps (user_dict) In [33]: user_jsonOut [33]:'{"name": "ithui", "sex": "\\ u7537"}'
You can also specify a converter when serializing. The optional parameter default is to turn any object into an object that can be sequentially listed as JSON. We only need to write a conversion function for User, and then pass the function into it:
In [28]: def user2dict (obj):...: return {'name': obj.name,' sex': obj.sex}.:: In [34]: user_json = json.dumps (user, default=user2dict) In [35]: user_jsonOut [35]:'{"name": "ithui", "sex": "\ u7537"}'
Although you can convert custom class objects into json, it is troublesome to customize different converters for different classes, so you want to serialize using the _ _ dict__ attribute of each class, which is a dict object that stores instance variables. There are a few exceptions, such as class that defines _ _ slots__
In [36]: user.__dict__Out [36]: {'name':' ithui', 'sex':' male'} In [41]: json.dumps (user.__dict__) Out [41]:'{"name": "ithui", "sex": "\\ u7537"}'
Note: if the property in the object is nested within another object that cannot be directly serialized by json, the _ _ dict__ attribute will not serialize properly.
Thank you for reading, the above is the content of "how to understand Python object serialization and deserialization". After the study of this article, I believe you have a deeper understanding of how to understand Python object serialization and deserialization. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.