官网解释:
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
andin
statements. This method corresponds to thetp_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 thetp_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__ 呢??求教!!!
原文地址:http://blog.51cto.com/13502993/2147531
时间: 2024-10-30 05:57:37