开发者

What are the iteration class methods next() and __next__() for, and what is the difference?

开发者 https://www.devze.com 2023-03-31 03:06 出处:网络
I am a little bit lost on python iterators. I occasionally use them, but I don\'t remember creating one myself开发者_如何转开发. I read from somewhere that I don\'t remember where, a code like this:

I am a little bit lost on python iterators. I occasionally use them, but I don't remember creating one myself开发者_如何转开发. I read from somewhere that I don't remember where, a code like this:

class Foo(object):
    def __init__(self):
        self.something = "initial_value"
    def __iter__(self):
        return self
    def next(self):
        # I don't quite remember what was here :S
        return self.something

I guess __iter__() method supposed to return an iterator, and that iterator should have a next method right? Then what about __next__() method? is it for directly iterating over a class without it returning another iterator with __iter__() method?


PEP 3114 renamed iterator.next() to iterator.__next__(). This was implemented in version 3.0. The link above contains all the gory details.


next has been renamed to __next__ in Python 3. As for what it does, it should return the next item, or raise StopIteration if there are no more.

0

精彩评论

暂无评论...
验证码 换一张
取 消