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

yield函数生成器

时间:2021-01-05 11:24:19      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:pytho   python   object   --   cep   exce   div   from   class   

在python中,有yield的函数是生成器函数

def gen(para):
    while True:
        yield para


print(next(gen(8)))
print(next(gen(88)))
print(next(gen(888)))

print("--------------------------------")

def gen2():
    l=["This","is","genernator","!","#"]
    yield l


print(gen2())
print(next(gen2()))


print("--------------------------------")

def gen3():
    l=["This","is","genernator","!","#"]
    yield from l
f=gen3()
while True:
    try:
        print(next(f))
    except StopIteration:
        break

print("--------------------------------")

def gen4():
    while True:
        r=yield
        print(r)


r=gen4()
r.send(None)
r.send("genernator1")
r.send("genernator2")
8
88
888
--------------------------------
<generator object gen2 at 0x019BBF08>
[This, is, genernator, !, #]
--------------------------------
This
is
genernator
!
#
--------------------------------
genernator1
genernator2

 

yield函数生成器

标签:pytho   python   object   --   cep   exce   div   from   class   

原文地址:https://www.cnblogs.com/pfeiliu/p/14221262.html

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