函数生成器

****生成器


生成器指生成器对象,可以由生成器表达式得到,也可以用yield关键字得到一个生成器函数,
调用这个函数得到一个生成器对象

延迟计算,惰性求值


yield:生成器返回值(惰性)


def inc():
for i in range(5):
print("~")
yield i
print("+++")

第一次 next(inc())
~
1

第二次next(inc())
+++
~ ~~
2
.
.
.

返回生成器对象


第一次先执行到yield语句,之后暂停
再次调用继续执行

出现return 或走完循环,报错误,代表生命走到尽头
return的值拿不到,抛出stopiteration异常

一般情况只要yield值

def inc():
def counter():
count = 0
while True:
count += 1
yield count
c = counter()
return lambda :next(c)
g = inc()
print(g())
print(g())
print(g())


send  
返回并进行值交互:

例:


def counter():
count = 0
while True:
count += 1
response = yield count ****
c = counter()

c.send(100) #response = 100
如果不用send,则response的值为None

yield from 语法:
for x in c: yield from c
yield x =>

猜你喜欢

转载自blog.51cto.com/13445354/2383349