python:dict转为class

基于网络传输的时候大部分数字都转成了字符串(二进制除外),因为常常碰到把字符串转为类的需求,json序列化是一种比较常见的方法,因此,接收到的json字串怎么反射回类呢?python当然没有反射一说,我们通常会把字符串先加载成json对象,这样,它就成为了一个dict,然后http://stackoverflow.com/questions/1305532/convert-python-dict-to-object上提供了一个巧妙的方法让dict直接变成class:

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.a
1
>>> s.b
2
当然,你要一个个地去改每个类的构造函数有点不现实,这提供了一个思路,我临时new一个类实例出来,然后再update它的字典就可以得到对象了:
import json
class student(object):
    name=""
    age=None
rtnvalue=remoteMethod(params**) #此处得到格式化为json格式的字符串
parsed=json.loads(rtnvalue,"utf-8")
st=student()
st.__dict__.update(parsed)
posted @ 2011-11-29 10:45  $walker  阅读(5728)  评论(0编辑  收藏  举报