题
根据有关 ABC, ,我只需要添加一个 next
能够子类的方法 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
, ,如表 PY3K文档. 。 (请记住阅读正确的版本!)
>>> 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)]
不隶属于 StackOverflow