相关疑难解决方法(0)

dict子类中的自定义迭代行为

我有一个类是标准dict的子类:

class Result(dict):

    """ Dict-like object with special methods """

    def content(self):
        return self.__getitem__('_content')

    def attrs(self):
        return self.__getitem__('_attrs')
Run Code Online (Sandbox Code Playgroud)

此对象中的示例表示:

{
    '_attrs': {'id': 1},
    'description': 'testtest',
    'calories': 1234,
    '_content': 'Sample content',
    'name': 'qwerty',
    'price': 12390
}
Run Code Online (Sandbox Code Playgroud)

我希望我的类在迭代时跳过带有下划线键的记录.

# data is Result()
>>> for item in data:
>>>    print(item)

'description'
'calories'
'name'
'price'
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

更新: 除了正确的答案,我还覆盖了keys()和items()方法来隐藏下划线键,即使这些方法将在迭代中使用:

def __iter__(self):
    for key in self.keys():
        yield key

def keys(self):
    return [key for key in super().keys() if key not in ['_attrs', '_content']]

def items(self):
    return [(key, …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

4
推荐指数
1
解决办法
86
查看次数

标签 统计

python ×1

python-3.x ×1