我有一个类是标准dict的子类:
class Result(dict):
""" Dict-like object with special methods """
def content(self):
return self.__getitem__('_content')
def attrs(self):
return self.__getitem__('_attrs')
此对象中的示例表示:
{
'_attrs': {'id': 1},
'description': 'testtest',
'calories': 1234,
'_content': 'Sample content',
'name': 'qwerty',
'price': 12390
}
我希望我的类在迭代时跳过带下划线键的记录。你知道吗
# data is Result()
>>> for item in data:
>>> print(item)
'description'
'calories'
'name'
'price'
我怎样才能做到这一点?你知道吗
更新: 除了正确的答案,我还重写了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, value) for key, value in super().items() if key not in ['_attrs', '_content']]
只需使用
startswith
方法。你知道吗只要实现
__iter__
。为了避免无限递归,使用.keys()
很重要:然后在迭代中跳过:
相关问题 更多 >
编程相关推荐