Python 2とPython 3対応の反復器

6891 ワード

ビルトインの反復器タイプを除いて、いずれかに__が含まれています.iter__関数、next(Python 2)または_next__関数のクラスはすべて反復器タイプです._iter__関数は反復可能なオブジェクトを返します.next(Python 2)または_next__の双曲線コサインを返します.
たとえば、1から100まで反復する整数反復器を作成します.
Python2
# coding=utf8

class IntegerIterator:
    def __init__(self):
        self._num = 0

    def __iter__(self):
        return self

    def next(self):
        if self._num == 100:
            raise StopIteration
        self._num += 1
        return self._num

if __name__ == '__main__':
    for a in IntegerIterator():
        print(a)

Python3
# coding=utf8

class IntegerIterator:
    def __init__(self):
        self._num = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self._num == 100:
            raise StopIteration
        self._num += 1
        return self._num

if __name__ == '__main__':
    for a in IntegerIterator():
        print(a)

Python 2と比べるとnext関数が__になりますnext__で行ないます.
Python 2とPython 3対応の反復器
Python 2とPython 3を互換性のある反復器を作成するには、次のように簡単です.
# coding=utf8

class IntegerIterator:
    def __init__(self):
        self._num = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self._num == 100:
            raise StopIteration
        self._num += 1
        return self._num

    next = __next__


if __name__ == '__main__':
    for a in IntegerIterator():
        print(a)
__next__関数を定義し、next__next__を指すように再定義します.このようなコードはエラーを報告しません.
# Python2
TypeError: instance has no next() method
# Python3
TypeError: iter() returned non-iterator of type '***'