編寫兼容Python2和Python3的迭代器

編寫一個整數迭代器,從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)

和Python2相比,next函數變成了__next__函數。

兼容Python2和Python3的迭代器

要編寫兼容Python2和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

    def next(self):
        return self.__next__()


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

同時添加next函數和__next__函數,並使用其中的一個調用另一個,並且要記得返回調用的結果。
這樣的代碼就不會報錯誤:

# Python2
TypeError: instance has no next() method
# Python3
TypeError: iter() returned non-iterator of type '***'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章