流畅的迭代器01.png
通过一个简单类的实现及优化过程,慢慢深入迭代的概念。
该类的主要功能如下:
- 传入一段话
- 可以迭代输出这段话的中所包含的每个词
第一版单词序列
这一版的单词序列实现如下两个接口:
-
__getitem__
根据索引获取数据 -
__len__
获取序列的长度
import re
import reprlib
RE_WORD = re.compile(r'\w+')
class Sentence(object):
def __init__(self, text):
self.text = text
self.words = RE_WORD.findall(text)
def __getitem__(self, index):
# 根据索引获取数据
return self.words[index]
def __len__(self):
# 获取序列的长度
return len(self.words)
def __repr__(self):
# reprlib.repr(xxx) 当xxx长度过长时会用...自动省略
return 'Sentence(%s)' % reprlib.repr(self.text)
In [1]: s = Sentence('"The time has come," the Walrus said,')
In [2]: s
Out[2]: Sentence('"The time ha... Walrus said,')
In [3]: s[0]
Out[3]: 'The'
In [4]: for word in s:
...: print(word)
...:
The
time
has
come
the
Walrus
said
当我们使用 for
循环去迭代的时候,for
循环会先去使用 iter()
函数从目标对象中获取一个迭代器,然后对此迭代器进行迭代。
所以,我们还可以这么去做迭代:
In [5]: sw = Sentence('"The time has come," the Walrus said,')
In [6]: sw_it = iter(sw)
In [7]: while True:
...: try:
...: print(next(sw_it))
...: except StopIteration:
...: del sw_it
...: break
...:
The
time
has
come
the
Walrus
said
这种写法,把 for
循环背后的迭代器显式地展现了出来。
iter()
获取迭代器的过程中会进行如下几个主要的操作:
- 检查有没有实现
__iter__
方法,如果有则通过该方法获取一个迭代器对象。 - 如果没有实现
__iter__
方法,那就会去找有没有实现__getitem__
方法,如果实现了,Python 会创建一个迭代器,该迭代器尝试从索引0开始返回数据(必须从0开始)。 - 如果
__getitem__
也没有实现,那就抛出TypeError
异常,表明C object is not iterable
。
注意: 如果我们需要自己实现一个迭代器,尽量去实现它的 __iter__
方法,这是现在的标准做法,__getitem__
只是为了兼容以前的代码做的补丁。
其实看源码中,对于迭代器对象的检查是这么做的:
class Iterator(Iterable):
__slots__ = ()
@abstractmethod
def __next__(self):
'Return the next item from the iterator. When exhausted, raise StopIteration'
raise StopIteration
def __iter__(self):
return self
@classmethod
def __subclasshook__(cls, C):
if cls is Iterator:
return _check_methods(C, '__iter__', '__next__')
return NotImplemented
如 __subclasshook__
方法所示,通过检查有没有 __iter__
和 __next__
两个方法来判断是否为迭代器。
因为我们的 Sentence
类是通过实现 __getitem__
的接口来获取迭代器的,所以虽然既能使用 for
循环迭代,又可以通过索引获取对应值,但是它本身并不可迭代,无法通过以下代码的验证:
from collections.abc import Iterable
issubclass(list, Iterable) # True
issubclass(Sentence, Iterable) # False
isinstance(list(), Iterable) # True
isinstance(Sentence(''), Iterable) # False
s_it = iter(Sentence(''))
isinstance(s_it, Iterable) # True
总结
- 使用
iter()
内置函数可以获取迭代器的对象。 - 如果对象实现了能返回迭代器的
__iter__
方法,那么对象就是可迭代的。 - 另外,如果实现了
__getitem__
方
法,而且其参数是从零开始的索引,这种对象也可以迭代,但不属于可迭代对象。