码迷,mamicode.com
首页 > 其他好文 > 详细

函数生成器

时间:2019-04-23 19:10:18      阅读:344      评论:0      收藏:0      [点我收藏+]

标签:不用   ret   print   计算   函数   return   from   res   返回值   

****生成器


生成器指生成器对象,可以由生成器表达式得到,也可以用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 =>

函数生成器

标签:不用   ret   print   计算   函数   return   from   res   返回值   

原文地址:https://blog.51cto.com/13445354/2383349

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!