4.3 我们想实现一个自定义的迭代模式,来区别常见的内建函数range reversed函数等
>>> def frange(start,stop,increment):
... x = start
... while x < stop:
... yield x
... x+=increment
>>> for n in frange(0,4,0.5):
... print(n)
...
0
0.5
1.0
1.5
2.0
2.5
3.0
3.5
>>> list(frange(0,1,0.125))
[0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
>>>
- 函数中只要出现了yield函数,就会变成一个生成器,与普通函数不同,生成器只有再响应了迭代操作时才运行,下面研究下他的机制
>>> def c(n):
... print('starting to count form',n)
... while n >0:
... yield n
... n -=1
... print('done')
...
>>> c =c(3)
>>> c
<generator object c at 0x104beff50>
>>> next(c)
starting to count form 3
3
>>> next(c)
2
>>> next(c)
1
>>> next(c)
done
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
- 这里函数的核心特性就是,在响应了迭代过程的next时才会运行,一旦生成器的函数返回,迭代也就停止了。
- 但是通常情况下for自带就处理了这些过程,不用再单独处理结束的返回