python 字典转成对象

python 字典转成对象_第1张图片

 

database = {
        "key1": {
            'period':999,
            "data": {
                'a':1,
                'b':2,
            }
        },
        "key2": {
            'period':1199,
            "data": {
                'a':11,
                'b':21,
            }
        },

    }

class Dict(dict):
    __setattr__ = dict.__setitem__
    __getattr__ = dict.__getitem__

def dict_to_object(dictObj):
    if not isinstance(dictObj, dict):
        return dictObj
    inst=Dict()
    for k,v in dictObj.items():
        inst[k] = dict_to_object(v)
    return inst
# 转换字典成为对象,可以用"."方式访问对象属性
res = dict_to_object(database)
print(res.key1)
print(res.key1.period)
print(res.key1.data.a)
{'period': 999, 'data': {'a': 1, 'b': 2}}
999
1

  

 

你可能感兴趣的:(python 字典转成对象)