簡體   English   中英

如何從 class 中返回嵌套字典鍵作為屬性?

[英]How do I return nested dictionary keys as attributes from a class?

我的 class: getNested() 中有一個 function:getNested() 將一堆數據作為嵌套字典。 在實例化 class 時,將這些數據轉換為我可以使用的屬性的最佳實踐是什么? 例如; 在下面的示例中運行 test.nestedDict.A 行將理想地返回 {'Aa': ['1', '2', '3',], 'Ab':'item'}。

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' # 

go 實現您想要的一種方法是定義和使用從dict繼承的助手 class 。 然后,在這個 class 中,將嵌套字典的鍵設置為 class 的屬性。

這看起來像:

class Nested(dict):
    def __init__(self, dict_):
        super(Nested, self).__init__()
        for k, v in dict_.items():
            if isinstance(v, dict):
                v = Nested(v)
            setattr(self, k, v)
            self.update({k: v})


class MyClass:
    def __init__(self):
        self.set_nested()

    def set_nested(self):
        nested_dict = {'A': {'Aa': ['1', '2', '3'], 'Ab': 'item'},
                       'B': {'Ba': ['4', '5', '6'], 'Bb': 'item2'}}
        self._nested_dict = Nested(nested_dict)

    @property
    def nested_dict( self ):
        return self._nested_dict

然后你可以這樣做:

>>> test = MyClass()
>>> test.nested_dict
{'A': {'Aa': ['1', '2', '3'], 'Ab': 'item'}, 'B': {'Ba': ['4', '5', '6'], 'Bb': 'item2'}}
>>> test.nested_dict.A
{'Aa': ['1', '2', '3'], 'Ab': 'item'}
>>> test.nested_dict.A.Aa
['1', '2', '3']
>>> test.nested_dict.A.Ab
'item'
>>> test.nested_dict['A']
{'Aa': ['1', '2', '3'], 'Ab': 'item'}

請注意,我允許自己更改變量和方法的名稱以符合PEP8 樣式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM