tags:

views:

56

answers:

3
class a(object):
    w={'a':'aaa','b':'bbb'}
    def __iter__(self):
        return iter(self.w)
    def next(self):#this is not be called
        print 'sss'
        for i in self.w:
            return i

b=a()
for i in b:
    print i

and what is Relations between __iter__ and next function.

thanks

+1  A: 

In __iter__() you return an iterator on the dict stored in self.w, not on the class itself. Returning self instead will fix that.

Ignacio Vazquez-Abrams
+2  A: 

I'm not entirely sure what you are asking, but the next() function isn't called because you never explicitly call it. You define __iter__, which gets called when you do:

for i in b:

This should implicitly call the .next() method of the iterator, but the iterator isn't a, but rather iter(self.w). As your object is not the iterator, its next() method is never called.

Hope this helps.

avpx
+2  A: 

next should remember the last position and return the next item (not always return the first item, like in your code), and when there are no further items, raise the StopIteration exception.

Also __iter__ should return the class itself.

See Python documentation for iterators.

In your case, using generator is more suitable:

class a(object):
    w={'a':'aaa','b':'bbb'}
    def __iter__(self):
        print 'sss'
        for i in self.w:
            yield i

b=a()
for i in b:
    print i
Iamamac