如何在self.dict中实现迭代器行为

时间:2014-05-29 01:48:06

标签: python iterator

我有一个像这样的容器对象:

class myclass():
    self.data = dict()
    self.otherattribute = 0 ## anything

如何编写__iter____next__来实现:

for i in myclass:

等于:

for i in myclass.data:

1 个答案:

答案 0 :(得分:2)

你可以让__iter__返回一个迭代器:

class myclass(object):
    def __init__:
        self.data = {}

    def __iter__(self):
        return iter(self.data)

有了这个,我可以这样做:

c = myclass()
c.data['key1'] = 'val1'
c.data['key2'] = 'val2'

for k in c:
    print k

哪个让我:

key2
key1