fab函数Python python fact函数( 二 )


Python
1
2
3
4
5
6
7
8
9
10
11
class Iter:
def __init__(self):
self.start=-1
def __iter__(self):
return self
def __next__(self):
self.start +=2
return self.start
I = Iter()
for count in range(5):
print(next(I))
题外话: 生成器是包含有__iter()和next__()方法的,所以可以直接使用for来迭代,而没有包含StopIteration的自编Iter来只能通过手动循环来迭代 。
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from collections import Iterable
from collections import Iterator
isinstance(odd_num, Iterable)
True
isinstance(odd_num, Iterator)
True
iter(odd_num) is odd_num
True
help(odd_num)
Help on generator object:
odd = class generator(object)
|Methods defined here:
|
|__iter__(self, /)
|Implement iter(self).
|
|__next__(self, /)
|Implement next(self).
......
看到上面的结果,现在你可以很有信心的按照Iterator的方式进行循环了吧!
在 for 循环执行时,每次循环都会执行 fab 函数内部的代码,执行到 yield b 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行 , 直到再次遇到 yield 。看起来就好像一个函数在正常执行的过程中被 yield 中断了数次 , 每次中断都会通过 yield 返回当前的迭代值 。
yield 与 return
在一个生成器中,如果没有return,则默认执行到函数完毕时返回StopIterationfab函数Python;
Python
1
2
3
4
5
6
7
8
9
10
11
def g1():
...yield 1
...
g=g1()
next(g)#第一次调用next(g)时,会在执行完yield语句后挂起,所以此时程序并没有执行结束 。
1
next(g)#程序试图从yield语句的下一条语句开始执行,发现已经到了结尾 , 所以抛出StopIteration异常 。
Traceback (most recent call last):
File "stdin", line 1, in module
StopIteration
如果遇到return,如果在执行过程中 return , 则直接抛出 StopIteration 终止迭代 。
Python
1
2
3
4
5
6
7
8
9
10
11
12
def g2():
...yield 'a'
...return
...yield 'b'
...
g=g2()
next(g)#程序停留在执行完yield 'a'语句后的位置 。
'a'
next(g)#程序发现下一条语句是return,所以抛出StopIteration异常,这样yield 'b'语句永远也不会执行 。
Traceback (most recent call last):
File "stdin", line 1, in module
StopIteration
如果在return后返回一个值,那么这个值为StopIteration异常的说明 , 不是程序的返回值 。
生成器没有办法使用return来返回值 。
Python
1
2
3
4
5
6
7
8
9
10
【fab函数Python python fact函数】11
def g3():
...yield 'hello'
...return 'world'
...
g=g3()
next(g)
'hello'
next(g)
Traceback (most recent call last):
File "stdin", line 1, in module
StopIteration: world
生成器支持的方法
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
help(odd_num)

推荐阅读