如何在Python 3类中包装此结构?

时间:2014-02-05 21:03:22

标签: python object data-structures python-3.x

我的代码中有一个结构,它是数组和dicts的混合,如下所示:

items=[{'key1': 'text',#start item1
        'key2': ['text', 'more text'],
        'key3': ['text', 'potentially more text'],
        'key4': 'text',
        'key5': 'text',
        'collection': [{'IDs': [0x01, 0x02],# binary data
                        'objects': [{'subkey1': 0xc3c3c3,# binary data
                                    'property': 0x00,# binary data
                                    'property': 0x90,# binary data
                                    'property': 0x29},# binary data
                                   {'subkey2': 0x53,# binary data
                                    'property': 0x20},# binary data
                                   {'subkey3': 0x56,# binary data
                                    'property': 0x27}]},# binary data
                       {'IDs': [0x01],# binary data
                        'objects': [{'subkey1': 0x90909090, # binary data
                                    'property': 0x00, # binary data
                                    'property': 0x90,# binary data
                                    'property': 0x29},# binary data
                                   {'subkey2': 0x53,# binary data
                                    'property': 0x20}]}]},
       {'key1': 'text',#start item 2
         ... }]# more items here

现在,我想创建一个可以在几种类型的对象中包含上述数据的对象结构(例如item类,collection类和object类,基于上面的名称)。例如,这将允许我轻松地对结构中的二进制数据进行转换。

但是,我正在努力寻找一种与上述内容完美匹配的结构,同时又是可扩展的(这样我就可以使用继承来添加到结构中)。

我的问题是(它可能是一个愚蠢的) - 你如何将上述结构表示为Python 3代码中的对象/类?

1 个答案:

答案 0 :(得分:0)

您需要的第一件事是更具体的名称。我将保留list items的外部cringe名称,但我将调用collectionsharps的字典将重命名为{{} 1}}这将是list PokePoke,每个listIDs property_nnclass Cringe: """ Contains several `keynn` attributes; `Sharps` is a list of `Pokes` """ def __init__(self): self.sharps = [] def keys(self): """ Return an iterator of `key...` attributes """ return (k for k in self.__dict__.keys() if k.startswith('key')) class Poke: """ Contains a list of ids, and possibly several Mulahs """ def __init__(self): self.IDs = [] self.mulahs = [] class Mulah: """ Contains one subkey, and possibly several properties """ def __init__(self, subkey, *properties): self.subkey = subkey for i, prop in enumerate(properties): name = 'property_%02d' % i setattr(self, name, prop) def properties(self): """ Return an iterator of `property_nn` attributes """ return (p for p in self.__dict__.keys() if p.startswith('property_')) s。

<div id="options">
    <p ng-repeat="answer in answers">
        <input type="text" ng-model="answer.text" />
    </p>
</div>

<button type="button" ng-click="newAnswer()">Add answer</button>

记住:名字很重要! :)