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)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM