Come faccio sottoclasse collections.Iterator?
-
02-10-2019 - |
Domanda
Secondo la documentazione sul ABCs , dovrei solo dovuto aggiungere un metodo next
per essere in grado di sottoclasse collections.Iterator
. Così, sto usando la seguente classe:
class DummyClass(collections.Iterator):
def next(self):
return 1
Tuttavia, ottengo un errore quando provo a un'istanza:
>>> x = DummyClass()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class DummyClass with abstract methods __next__
Sto indovinando che sto facendo qualcosa di stupido, ma io non riesco a capire di cosa si tratta. Qualcuno può far luce su questo? Potrei aggiungere un metodo __next__
, ma ho avuto l'impressione che fosse solo per le classi C.
Soluzione
Sembra che si sta utilizzando Python 3.x. Il tuo codice funziona bene su 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)]
Ma su Python 3.x, è necessario implementare __next__
invece di next
, come indicato nella tabella di la py3k doc . (Ricordati di leggere la versione corretta!)
>>> 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)]
Questa modifica è introdotta da PEP-3114 - Rinominare iterator.next()
a iterator.__next__()
.