我如何继承collections.Iterator?

Jas*_*ker 2 python collections iterator abc

根据关于ABC的文档,我应该只需要添加一个next方法来进行子类化collections.Iterator.所以,我正在使用以下类:

class DummyClass(collections.Iterator):
    def next(self):
        return 1
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试实例化它时出现错误:

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

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

ken*_*ytm 7

看起来你正在使用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)]
Run Code Online (Sandbox Code Playgroud)

但是在Python 3.x上,你应该实现__next__而不是next,如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)]
Run Code Online (Sandbox Code Playgroud)

此更改由PEP-3114iterator.next()iterator.__next__()引入- 重命名.