歡迎您光臨本站 註冊首頁

Python轉換字典成為對象,可以用

←手機掃碼閱讀     retouched @ 2020-05-12 , reply:0

我就廢話不多說了,大家還是直接看代碼吧!
database = [ { "name": "18D_Block", "xcc":{ "component": { "core":[], "platform":[] }, }, "uefi":{ "component": { "core":[], "platform":[] }, } } ] 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[0]) print res.name print res.xcc print res.xcc.component print res.xcc.component.core
補充知識:[Python] 字典 vars()函數:以字典類型提取對象的屬性和屬性值
功能
提取對象的屬性和屬性值,返回值為dictionary字典類型。
語法
vars(object)
實例
>>>print(vars()) {'__builtins__':

, '__name__': '__main__', '__doc__': None, '__package__': None} >>> class Test: ... a = 1 ... >>> print(vars(Test)) {'a': 1, '__module__': '__main__', '__doc__': None} >>> test = Test() >>> print(vars(test)) {}
對於 x = 1,這樣的一個賦值語句,我們在執行後,名稱 x 引用到值 1。這就像字典一樣,鍵引用值,當然,變量和所對應的值用的是個"不可見"的字典。我們可以使用 vars() 函數來返回這個字典:
>>> x = 1 >>> scope = vars() >>> scope["x"] 1


[retouched ] Python轉換字典成為對象,可以用已經有354次圍觀

http://coctec.com/docs/python/shhow-post-234040.html