Python实现自定义迭代器类

Python里迭代器用法如下,主要用到了iter()和next()两个方法

>>> l = [1, 3, 5, 7, 9]
>>> iter = iter(l)
>>> next(iter)
1
>>> next(iter)
3
>>> next(iter)
5
>>> next(iter)
7
>>> next(iter)
9
>>> next(iter)
Traceback (most recent call last):
  File "", line 1, in 
StopIteration

可以捕获一下StopIteration异常,以免超过了迭代器中元素的个数

#!/usr/bin/env python3

# -*- coding: utf-8 -*-
# Time : 2019/12/27 11:13 下午
# Auth : lihui
# File : my_iter.py

l = [1, 3, 5, 7, 9]
it = iter(l)
while True:
try:
print(next(it))
except StopIteration:
break

假如要自己实现一个迭代器类,则需要实现这两个方法,其中:

iter():将参数对象转换为迭代器对象

next():从迭代器对象中取出下一项

容器调用iter()方法,会返回一个定义了__next__()方法的迭代器对象,该对象逐一访问容器中的元素;因此可以定义一个__iter__()方法来返回一个带有__next__()方法的对象,如果类已经定义了__next__(),那么__iter__()可以直接返回self

有关迭代器的定义,可以查看官方文档:https://docs.python.org/zh-cn/3/tutorial/classes.html?highlight=iterator#iterators

可以实现一个倒序的迭代器类,完全按照迭代器的定义即可

#!/usr/bin/env python3

# -*- coding: utf-8 -*-
# Time : 2019/12/27 11:13 下午
# Auth : lihui
# File : my_iter.py

class Reverse:
def __init__(self, data):
self.data = data
self.index = len(data)

def __iter__(self):
return self

def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]


if __name__ == '__main__':
l = [1, 3, 5, 7, 9]
rev = Reverse(l)
while True:
try:
print(next(rev))
except StopIteration:
break

或者交互式测试

>>> from my_iter import Reverse
>>> l = [1, 3, 5, 7, 9]
>>> rev = Reverse(l)
>>> next(rev)
9
>>> next(rev)
7
>>> next(rev)
5
>>> next(rev)
3
>>> next(rev)
1
>>> next(rev)
Traceback (most recent call last):
  File "", line 1, in 
  File "/Users/lihui/Documents/Python/iter/my_iter.py", line 18, in __next__
    raise StopIteration
StopIteration

这样就实现了一个自定义的迭代器类

OVER

发表回复