Python轉換字典成為對象,可以用"."方式訪問對象屬性實例
我就廢話不多說了,大家還是直接看代碼吧!
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.nameprint res.xccprint res.xcc.componentprint res.xcc.component.core
補充知識:[Python] 字典 vars()函數:以字典類型提取對象的屬性和屬性值
功能
提取對象的屬性和屬性值,返回值為dictionary字典類型。
語法
vars(object)
實例
>>>print(vars()){’__builtins__’: <module ’__builtin__’ (built-in)>, ’__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
以上這篇Python轉換字典成為對象,可以用'.'方式訪問對象屬性實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
