我有一个像这样的容器对象:
class myclass():
self.data = dict()
self.otherattribute = 0 ## anything
如何编写__iter__
和__next__
来实现:
for i in myclass:
等于:
for i in myclass.data:
答案 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