简体   繁体   English

有人可以告诉我如何理解下面的python程序(我们使用__iter __()做什么?)

[英]can someone tell me how to understand the python program below(what do we use __iter__() to do?)

can someone tell me how that can happen? 有人可以告诉我怎么回事吗?

I have a program like this: 我有一个这样的程序:

class Fib(object):

    def __init__(self):
        self.a, self.b = 0, 1 

    def __iter__(self):
        return self 

    def next(self):
        self.a, self.b = self.b, self.a + self.b 
        if self.a > 100000:
            raise StopIteration();
        return self.a 

if I enter : 如果我输入:

>>> for n in Fib():
...     print n

the output is: 输出为:

1
1
2
3
5
...
46368
75025

the question is that I have no idea how __iter__ is related to next(self), and how computer read the program?can someone help me explain this program? 问题是我不知道__iter__与next(self)有什么关系,以及计算机如何读取该程序?有人可以帮我解释一下该程序吗?

Check this out 看看这个

 class Fib:                                        ①
     def __init__(self, max):                      ②
         self.max = max

     def __iter__(self):                           ③
         self.a = 0
         self.b = 1
         return self

     def next(self):                           ④
         fib = self.a
         if fib > self.max:
             raise StopIteration                   ⑤
         self.a, self.b = self.b, self.a + self.b
         return fib                                ⑥

Thoroughly confused yet? 彻底困惑了吗? Excellent. 优秀的。 Let's see how to call this iterator: 让我们看看如何调用此迭代器:

from fibonacci2 import Fib
for n in Fib(1000): 
    print n,

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 987

Here's what happens: 这是发生了什么:

The for loop calls Fib(1000), as shown. for循环调用Fib(1000),如图所示。 This returns an instance of the Fib class. 这将返回Fib类的实例。 Call this fib_inst. 将此称为fib_inst。 Secretly, and quite cleverly, the for loop calls iter(fib_inst), which returns an iterator object. for循环秘密地并且非常巧妙地调用iter(fib_inst),它返回一个迭代器对象。 Call this fib_iter. 将此称为fib_iter。 In this case, fib_iter == fib_inst, because the iter () method returns self, but the for loop doesn't know (or care) about that. 在这种情况下,fib_iter == fib_inst,因为iter ()方法返回self,但是for循环对此并不了解(或不在乎)。 To “loop through” the iterator, the for loop calls next(fib_iter), which calls the next () method on the fib_iter object, which does the next-Fibonacci-number calculations and returns a value. 为了“遍历”迭代器,for循环调用next(fib_iter),该调用在fib_iter对象上调用next ()方法,该对象执行next-Fibonacci-number计算并返回一个值。 The for loop takes this value and assigns it to n, then executes the body of the for loop for that value of n. for循环使用该值并将其分配给n,然后针对该n值执行for循环的主体。 How does the for loop know when to stop? for循环如何知道何时停止? I'm glad you asked! 我很高兴你问! When next(fib_iter) raises a StopIteration exception, the for loop will swallow the exception and gracefully exit. 当next(fib_iter)引发StopIteration异常时,for循环将吞下该异常并正常退出。 (Any other exception will pass through and be raised as usual.) And where have you seen a StopIteration exception? (任何其他异常都会通过并照常引发。)您在哪里看到了StopIteration异常? In the next () method, of course! 当然,在next ()方法中!

In Python, there is the concept of iterables and iterators. 在Python中,存在可迭代和迭代器的概念。 Loosely, an iterable is anything with an iter method. 松散地,可迭代是使用iter方法的任何事情。 An example is a list. 一个示例是列表。 When a for loop is ran on this list, say: 当在此列表上运行for循环时,请说:

for i in range(5):
        print i

Python returns an iterator, which automagically calls produces all the result. Python返回一个迭代器,该迭代器自动调用会产生所有结果。

Now an iterator(not to be confused with iterables) by itself is any object with an iter function and a next method. 现在,迭代器(不要与iterables混淆)本身就是具有iter函数和next方法的任何对象。 When this iterator loops, it calls the next method on every loop, which basically produces the next output, much like a for loop produces outputs within the range. 当此迭代器循环时,它将在每个循环上调用next方法,基本上会产生下一个输出,就像for循环会生成范围内的输出。

When the next call reaches the last element, a StopIteration error is raised, ending the loop. 当下一个调用到达最后一个元素时,将引发StopIteration错误,从而结束循环。 This is very analogous to how a for loop works behind the scenes. 这非常类似于for循环在幕后的工作方式。

In a nutshell, what your code is doing is that it is creating an iterator, and defining what happens every time the iterator wants to fetch the next value ie the next() method. 简而言之,您的代码正在执行的操作是创建一个迭代器,并定义每次迭代器要获取下一个值(即next()方法)时发生的情况。

Python has iterators, similar to Java's Iterator and C#'s IEnumerable(T). Python具有迭代器,类似于Java的迭代器和C#的IEnumerable(T)。

Read this: 读这个:

https://docs.python.org/2/library/stdtypes.html#iterator-types https://docs.python.org/2/library/stdtypes.html#iterator-types

https://www.python.org/dev/peps/pep-0234/ https://www.python.org/dev/peps/pep-0234/

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

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