python字典转对象


class UpdateParams:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

    def __getattr__(self, item):
        print(f"没有该属性:{item}")
        return None


def json2obj(json_data):
    d = UpdateParams.__new__(UpdateParams)
    d.__dict__.update(json_data)
    return d


if __name__ == '__main__':
    j = {'name': "zhangsan", 'age': 28, 'gender': '男', 'score': {"english": 90, "math": 80, "history": 65},
         'like': ["tv", "dvd", "phone"]}
    obj = json2obj(j)
    print(obj.name)
    print(obj.age)
    print(obj.gender)
    print(obj.score)
    score = json2obj(obj.score)
    print(score.english)
    print(obj.like)

posted @ 2020-09-10 23:02  公众号python学习开发  阅读(1610)  评论(0编辑  收藏  举报