我有一个类是标准字典的子类:
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'
我怎样才能做到这一点?
UPDATE:除了正确答案之外,我还重写了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']]
只需实施__iter__
。使用很重要.keys()
,为了避免无限递归:
class Result(dict):
def __iter__(self):
for key in self.keys():
if not(isinstance(key, str) and key.startswith("_")):
yield key
那么它会在迭代中被跳过:
>>> r=Result({1:1,"_foo":2, "bar":3})
>>> for item in r:
... print(item)
...
1
bar
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)