|
|
发表于 2018-4-27 02:08:12
|
显示全部楼层
Python魔术方法__next__() => next()函数
==========================
>>> g = (x**2 for x in range(1, 6))
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
25
>>> next(g)
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
next(g)
StopIteration
生成器是一次性消费,用完就没了。
我们可以实现自己的生成器函数,使用yield关键字
>>> def gen():
yield 1
>>> next(a)
1
>>> next(a)
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
next(a)
StopIteration
因为没有while循环作为外层保护,这里gen在生产了1后就壮烈的死掉了。
更一般的是迭代器,任何实现了【迭代协议】的类都是迭代器,迭代器的next函数返回自身迭代对象
>>> class It(object):
def __init__(self):
self.a = 1
self.b = 1
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.a+self.b, self.a
return self.a
>>> d = It()
>>> next(d)
2
>>> next(d)
3
>>> next(d)
5
>>> next(d)
8
>>> next(d)
13
>>>
生成器可以看成是迭代器的特殊情况 |
|