next()和__next __()的迭代类方法有什么用,有什么区别? [英] What are the iteration class methods next() and __next__() for, and what is the difference?

查看:385
本文介绍了next()和__next __()的迭代类方法有什么用,有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python迭代器上有点迷路了.我偶尔使用它们,但我不记得自己创建一个.我从某个地方不记得的地方读到了这样的代码:

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

我猜想__iter__()方法应该返回迭代器,并且该迭代器应该具有下一个方法吧?那__next__()方法呢?是直接在类上迭代而不用__iter__()方法返回另一个迭代器吗?

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 重命名iterator.next()iterator.__next__().这是在3.0版中实现的.上面的链接包含所有血腥细节.

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

这篇关于next()和__next __()的迭代类方法有什么用,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆