Python 如何将嵌套字典键作为类的属性返回?
我的类中有一个函数:getNested(),它作为嵌套字典获取一组数据。将这些数据转换为属性的最佳实践是什么,然后我可以在实例化类时使用这些属性?如;运行下面示例中的line test.nestedDict.A,理想情况下会返回{'Aa':['1','2','3',],'Ab':'item'}Python 如何将嵌套字典键作为类的属性返回?,python,python-2.7,class,attributes,Python,Python 2.7,Class,Attributes,我的类中有一个函数:getNested(),它作为嵌套字典获取一组数据。将这些数据转换为属性的最佳实践是什么,然后我可以在实例化类时使用这些属性?如;运行下面示例中的line test.nestedDict.A,理想情况下会返回{'Aa':['1','2','3',],'Ab':'item'} class MyClass( object ): def __init__( self ): self._nestedDict = None self.getNes
class MyClass( object ):
def __init__( self ):
self._nestedDict = None
self.getNested()
def getNested( self ):
self._nestedDict = {'A':{'Aa': ['1', '2', '3',], 'Ab':'item'}, 'B':{'Ba': ['4', '5', '6',], 'Bb':'item2'} }
@property
def nestedDict( self ):
return self._nestedDict
test = MyClass()
test.nestedDict
# Result: {'A': {'Aa': ['1', '2', '3'], 'Ab': 'item'},'B': {'Ba': ['4', '5', '6'], 'Bb': 'item2'}} #
test.nestedDict['A']
# Result: {'Aa': ['1', '2', '3'], 'Ab': 'item'} #
test.nestedDict.A
# Error: AttributeError: line 1: 'dict' object has no attribute 'A' #
实现所需的一种方法是定义并使用从
dict
继承的helper类。然后,在此类中,将嵌套字典的键设置为该类的属性
这看起来像:
类嵌套(dict):
定义初始值(自我、指令):
超级(嵌套,自)。\uuuu初始化
对于dict.items()中的k,v:
如果存在(v,dict):
v=嵌套(v)
setattr(自、k、v)
self.update({k:v})
类别MyClass:
定义初始化(自):
self.set_嵌套()
def set_嵌套(自):
嵌套的dict={'A':{'Aa':['1','2','3'],'Ab':'item'},
'B':{'Ba':['4','5','6'],'Bb':'item2'}
self.\u嵌套的\u dict=嵌套的(嵌套的\u dict)
@财产
def嵌套目录(自身):
返回自我。\u嵌套\u指令
然后,您可以使用它执行以下操作:
>test=MyClass()
>>>test.nested_dict
{'A':{'Aa':['1','2','3'],'Ab':'item'},'B':{'Ba':['4','5','6'],'Bb':'item2'}
>>>测试。嵌套的_dict.A
{'Aa':['1','2','3'],'Ab':'item'}
>>>测试A.A.Aa
['1', '2', '3']
>>>test.nested_dict.A.Ab
“项目”
>>>test.nested_dict['A']
{'Aa':['1','2','3'],'Ab':'item'}
请,请注意,我允许自己更改变量和方法的名称,以符合像您使用的
nestedDict
这样的字典不支持这一点。那么您将如何将一组未知数据作为属性添加到类中?@Antony您正在显示的*不会将这些属性作为类的成员MyClass
,但是作为teste.nestedDict
返回的任何内容的成员。这段代码不错!虽然这确实回答了我最初的问题,但现在这些属性是在helper类中定义的。因此,如果我在MyClass中添加一个def _usetattr _;():我实际上无法截获这些属性的任何设置。现在,我将尝试在helper类中做一个变通。谢谢