Wie kann ich Unterklasse collections.Iterator?
-
02-10-2019 - |
Frage
Nach der Dokumentation auf ABCs , ich sollte nur eine next
Methode in der Lage sein zu Unterklasse collections.Iterator
hinzufügen. Also, ich bin mit der folgenden Klasse:
class DummyClass(collections.Iterator):
def next(self):
return 1
Allerdings habe ich einen Fehler, wenn ich versuche, es zu instanziieren:
>>> x = DummyClass()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class DummyClass with abstract methods __next__
Ich vermute, dass ich tue etwas dumm, aber ich kann nicht herausfinden, was es ist. Kann jemand etwas Licht auf das? Ich könnte eine __next__
Methode hinzufügen, aber ich habe den Eindruck, dass nur für C-Klassen war.
Lösung
Sieht aus wie Sie verwenden Python 3.x Der Code funktioniert auf 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)]
Aber auf Python 3.x, sollten Sie __next__
statt next
implementieren, wie in der Tabelle von die py3k doc . (Denken Sie daran, die richtige Version zu lesen!)
>>> 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)]
Diese Änderung wird eingeführt von PEP-3114 - Umbenennung iterator.next()
zu iterator.__next__()
.