python Class: 面向对象高级编程 __iter__ 和 next()
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Class: 面向对象高级编程 __iter__ 和 next()相关的知识,希望对你有一定的参考价值。
官网解释:
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__ 呢??求教!!!
以上是关于python Class: 面向对象高级编程 __iter__ 和 next()的主要内容,如果未能解决你的问题,请参考以下文章
python Class: 面向对象高级编程 __iter__ 和 next()
python Class:面向对象高级编程 __str__ / __repr__