سؤال

وفقا للوثائق في ABCs, ، يجب أن أضطر فقط لإضافة ملف 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)]

تم تقديم هذا التغيير بواسطة PEP-3114-إعادة تسمية iterator.next() إلى iterator.__next__().

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top