简体   繁体   English

为什么以下python代码有效?

[英]Why the following python code works?

class Square:                          
    def __init__(self,start,stop):     
        self.value = start - 1
        self.stop = stop
    def __iter__(self):
        return  self           
    def next(self):
        if self.value == self.stop:
            raise   StopIteration                                             
        self.value += 1
        return self.value ** 2
for i in Square(1,4):
    print i,

Which outputs 哪个输出

1 4 9 16 1 4 9 16

why wouldn't it? 为什么不呢? It looks like a normal iterator to me... 在我看来,这就像是普通的迭代器...

the next() method is a 'known' method in python that along with the __iter__() method signals a generator. next()方法是python中的“已知”方法,它与__iter__()方法一起发出信号给生成器。

Here is the python docs on iterators. 这是迭代器上的python文档。

这是一个Python迭代器:每次循环时,都会调用next()方法

It's an iterator. 这是一个迭代器。

Normally though, you would write it using yield. 不过,通常,您将使用yield来编写它。

def Square(start, stop):
    for value in xrange(start, stop + 1):
        yield value ** 2

for i in Square(1, 4):
    print i,

The typical Python iteration protocol: for y in x... is as follows: 典型的Python迭代协议: for y in x...如下:

iter = x.__iter__()         # get iterator
try:
    while 1:
        y = iter.next()         # get each item
        ...                     # process y
except StopIteration: pass  # iterator exhausted

from http://www.boost.org/doc/libs/1_41_0/libs/python/doc/tutorial/doc/html/python/iterators.html 来自http://www.boost.org/doc/libs/1_41_0/libs/python/doc/tutorial/doc/html/python/iterators.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM