在定义的对象中,一些值保存在dict
中,我希望迭代dict
中的内容,就像引用普通dict
时一样,因此可以直接访问使用[]
,并使用例如循环.items()
。代码结构是:
class Klass:
def __init__(self, values):
self.values = values
self.more = None
def __getitem__(self, name):
return self.values[name]
def __iter__(self):
pass # TBD[How to make this ?]
d = {'alfa': 1, 'bravo': 2, 'charlie': 3}
k = Klass(d)
for key in k:
print(key) # Expected to print keys from self.values
for (key, value) in k.items():
print(key, value) # Expected to print key and value from self.values
for key in k.keys():
print(key) # Expected to print key from self.values
for value in k.values():
print(value) # Expected to print value from self.values
如何编写__iter__
和其他必需的方法,以便通过Klass实例进行这种访问?
答案 0 :(得分:8)
您必须自己实施.keys()
,.values()
和.items()
方法;与__iter__
一起,他们都可以将实际工作委托给self.values()
词典:
class Klass:
def __init__(self, values):
self._values = values
self.more = None
def __getitem__(self, name):
return self._values[name]
def __iter__(self):
return iter(self._values)
def keys(self):
return self._values.keys()
def items(self):
return self._values.items()
def values(self):
return self._values.values()
我重命名了该属性以避免屏蔽.values()
方法。
将__iter__
委托给字典上的迭代(通过键)的最简单方法是使用iter()
function来获取字典对象的迭代器。
要明确:__iter__
在如何处理.keys()
,.values()
和.items()
方面不起作用;后者只是更多方法。
答案 1 :(得分:1)
class Klass(dict):
def __init__(self, *arg, **kw):
super(Klass, self).__init__(*arg, **kw)
self.choosebettername = super(Klass, self).keys()
def __iter__(self):
return iter(self.choosebettername)
def keys(self):
return self.choosebettername
def itervalues(self):
return (self[key] for key in self)
d = {'alfa': 1, 'bravo': 2, 'charlie': 3}
k = Klass(d)
for key in k:
print(key) # Expected to print keys from self.values
for (key, value) in k.items():
print(key, value) # Expected to print key and value from self.values
for key in k.keys():
print(key) # Expected to print key from self.values
print(k.values())
for value in k.values():
print(value) # Expected to print value from self.values