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