zoukankan      html  css  js  c++  java
  • __iter__

    __iter__

      如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法,该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的next()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。

      我们以斐波那契数列为例,写一个Fib类,可以作用于for循环:

      

      现在,试试把Fib实例作用于for循环:

      

    container.__iter__()

      Return an iterator object. The object is required to support the iterator protocol described below.

    The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:

    iterator.__iter__()

    Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and instatements.

    iterator.__next__()

    Return the next item from the container. If there are no further items, raise the StopIteration exception. 

    参考:https://docs.python.org/3.5/library/stdtypes.html#typeiter

  • 相关阅读:
    随机数
    质数
    猜数
    失败
    判断质数
    2019.7.21记录
    9*9乘法表
    小人
    奔跑的字母

  • 原文地址:https://www.cnblogs.com/tekkaman/p/5715405.html
Copyright © 2011-2022 走看看