如何继承collections.Iterator?

问题描述:

根据ABCs的文档,我只需要添加一个next方法就可以继承collections.Iterator。所以,我用下面的类:如何继承collections.Iterator?

class DummyClass(collections.Iterator): 
    def next(self): 
     return 1 

不过,我得到一个错误,当我尝试实例吧:

>>> x = DummyClass() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: Can't instantiate abstract class DummyClass with abstract methods __next__ 

我猜,我做了一些愚蠢的,但我无法弄清楚它是什么。任何人都可以对此有所了解吗?我可以添加一个__next__方法,但我的印象仅限于C类。

看起来你使用的是Python 3.x.您的代码在Python 2.x上正常工作。

>>> import collections 
>>> class DummyClass(collections.Iterator): 
...  def next(self): 
...   return 1 
... 
>>> x = DummyClass() 
>>> zip(x, [1,2,3,4]) 
[(1, 1), (1, 2), (1, 3), (1, 4)] 

但是Python的3.x的,你应该实现的__next__代替next,如在the py3k doc表所示。 (请务必阅读正确的版本!)

>>> import collections 
>>> class DummyClass(collections.Iterator): 
...  def next(self): 
...   return 1 
... 
>>> x = DummyClass() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: Can’t instantiate abstract class DummyClass with abstract methods __next__ 
>>> class DummyClass3k(collections.Iterator): 
...  def __next__(self): 
...   return 2 
... 
>>> y = DummyClass3k() 
>>> list(zip(y, [1,2,3,4])) 
[(2, 1), (2, 2), (2, 3), (2, 4)] 

此更改是由PEP-3114 — Renaming iterator.next() to iterator.__next__()介绍的。

+0

正如[ideone](http://ideone.com/6cxGR)上所见 – NullUserException 2010-09-13 19:48:43

+0

它必须是一个Python 2.6.1在Mac上的错误。 – 2010-09-13 20:28:20

+0

为了澄清我最后的评论,我*正在运行python 2.x.它似乎已经在OS X附带的版本之后的版本中得到修复。 – 2010-11-22 19:44:47