首页 > 编程语言 > 详细

python Class: 面向对象高级编程 __iter__ 和 next()

时间:2018-07-20 12:23:47      阅读:261      评论:0      收藏:0      [点我收藏+]
官网解释:

New in version 2.2.

  • iterator.__iter__()

  • Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and instatements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

  • iterator.next()

  • Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.


也就是说 __iter__与next()是配套使用的。


Fibonacci数列:

#!/usr/bin/python

# -*- coding: utf-8 -*-


class Fibo(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 > 10000:

            raise StopIteration()

        return self.a, self.b



for n in Fibo():

    print n


运行失败:

技术分享图片


怎么用class做才能成功呢?????

后来,才发现,我2.7版本的解释器不支持,用网页上的Python3在线编程解释器完美运行。。。。。。is ri le gou le.

附使用的python3环境:http://www.dooccn.com/python3/


请问各位大佬,在2.7版本中我该怎么使用 __iter__ 呢??求教!!!


python Class: 面向对象高级编程 __iter__ 和 next()

原文:http://blog.51cto.com/13502993/2147531

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!