Python: Convert dict to class

Source: Internet
Author: User

During network-based transmission, most numbers are converted to strings (except binary). JSON serialization is a common method because it is often required to convert strings into classes, how do I return the received JSON string to the class? Python has no reflection. We usually load the string into a JSON object first, so that it becomes a dict, and then parse:

Class struct: def _ init _ (self, ** entries): Self. _ dict __. update (entries) then, you can use: >>> ARGs = {'A': 1, 'B ': 2 }>>> S = struct (** ARGs) >>>s <__ main __. struct instance at 0x01d6a738 >>> S. a1 >>>> S. b2
Of course, it is unrealistic to change the constructor of each class one by one. This provides an idea. I will temporarily create a new class instance, then update its dictionary to get the object:
Import jsonclass student (object): name = "" age = nonertnvalue = remotemethod (Params **) # The formatted JSON string parsed = JSON is obtained here. loads (rtnvalue, "UTF-8") ST = student () ST. _ dict __. update (parsed)

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.