Python轉(zhuǎn)換字典成為對(duì)象,可以用"."方式訪問(wèn)對(duì)象屬性實(shí)例
我就廢話不多說(shuō)了,大家還是直接看代碼吧!
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# 轉(zhuǎn)換字典成為對(duì)象,可以用'.'方式訪問(wèn)對(duì)象屬性res = dict_to_object(database[0])print res.nameprint res.xccprint res.xcc.componentprint res.xcc.component.core
補(bǔ)充知識(shí):[Python] 字典 vars()函數(shù):以字典類型提取對(duì)象的屬性和屬性值
功能
提取對(duì)象的屬性和屬性值,返回值為dictionary字典類型。
語(yǔ)法
vars(object)
實(shí)例
>>>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)){}
對(duì)于 x = 1,這樣的一個(gè)賦值語(yǔ)句,我們?cè)趫?zhí)行后,名稱 x 引用到值 1。這就像字典一樣,鍵引用值,當(dāng)然,變量和所對(duì)應(yīng)的值用的是個(gè)'不可見'的字典。我們可以使用 vars() 函數(shù)來(lái)返回這個(gè)字典:
>>> x = 1>>> scope = vars()>>> scope['x']1
以上這篇Python轉(zhuǎn)換字典成為對(duì)象,可以用'.'方式訪問(wèn)對(duì)象屬性實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
