+ -
当前位置:首页 → 问答吧 → python迭代器使用

python迭代器使用

时间:2011-03-02

来源:互联网

定义了如下一个类:
class Fibs:
  def __init__(self):
  self.a=0
  self.b=1
  def next(self):
  self.a,self.b=self.b,self.a+self.b
  return self.a
  def __iter__(self):
  return self
使用
fibs=Fibs()
for f in fibs:
if f>1000:
print(f)
break
时候提示
Traceback (most recent call last):
  File "<pyshell#80>", line 1, in <module>
  for f in fibs:
TypeError: iter() returned non-iterator of type 'Fibs'
请问如何解决?

作者: zsuguangh   发布时间: 2011-03-02

还有一个问题就是我按《Python基础教程》中输入
it=iter([1,2,3])
it.next()
提示
Traceback (most recent call last):
  File "<pyshell#82>", line 1, in <module>
  it.next()
AttributeError: 'list_iterator' object has no attribute 'next'
但是书上的例子是有结果的,请问是python的版本问题么?

作者: zsuguangh   发布时间: 2011-03-02

1. 贴代码用代码标签。
2. 你的python什么版本?

作者: iambic   发布时间: 2011-03-02


程序都是没有问题的


你用的是什么版本的python?

作者: runer   发布时间: 2011-03-02

刚刚试过了,python2.6是可以通过的,我现在用python3.1的话将it.next()改成it.__next__()也可以了,估计是python版本问题

作者: zsuguangh   发布时间: 2011-03-02

晕,py3系列和py2系列是不兼容的

目前市面上的书应该还没有关于3 的

作者: runer   发布时间: 2011-03-02