循环对象
Python中的许多语法结构都是由对象实现的,循环就可以通过对象实现。
循环对象并不是在Python诞生之初就存在的,但它的发展极为迅速,特别是在Python 3时代,循环对象正在成为循环的标准形式。
那么,什么是循环对象呢?
所谓的循环对象包含有一个__next__()方法。这个方法的目的是生成循环的下一个结果。
在生成过循环的所有结果之后,该方法将抛出StopIteration异常。
循环接收到这个异常,就会知道循环已经结束,将停止调用__next__()。
我们用内置函数iter()把一个列表转变为循环对象。这个循环对象将拥有__next__()方法。我们多次调用__next__()方法,将不断返回列表的值,直到出现异常:
在python编译器中执行如下代码:
接着,在python编译器中执行如下代码:
我们上面重复调用__next__()的过程,就相当于手动进行了循环。我们可以把循环对象包裹在for中自动进行循环:
for itemin iter([1, 2]): print(item)
这里,for结构自动调用__next__()方法,将该方法的返回值赋予给item。循环知道出现StopIteration的时候结束。
当然,我们可以省去内置函数iter的转换。这是因为,for结构会自动执行这一转换。
相对于序列,循环对象的好处在于:不用在循环还没开始的时候,就生成要使用的元素。所有要使用的元素可以在循环过程中逐渐生成。这样,不仅节省了空间,提高了效率,还会使编程更加灵活。