您的位置:首页 > 编程语言 > Python开发

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

2018-07-20 10:41 465 查看
官网解释: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
in
statements. 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 iter