gpt4 book ai didi

python - yield (yield) 有什么作用?

转载 作者:太空狗 更新时间:2023-10-30 01:56:58 28 4
gpt4 key购买 nike

自 python 2.5 以来,可以将 send()throw()close() 放入生成器中。在定义的生成器中,可以通过执行以下操作来“捕获”发送的数据:

def gen():
while True:
x = (yield)
if x == 3:
print('received 3!!')
break
else:
yield x

我想玩的是做类似的事情:

def gen2():
while True:
yield (yield)

注意到它是一个合法的生成器,可以做一些事情..我想弄清楚的第一件事是:

这样写有什么好的用法吗?

同样在做类似的事情时:

g = gen2()
next(g)
g.send(10) # output: 10
g.send(2) # output: nothing
g.send(3) # output: 3
g.send(44) # output: nothing

为什么每秒“发送”都没有做任何事情?

最佳答案

yield (yield) 首先从内部 yield 产生 None。然后它从 sendnext 接收一个值。内部 yield 评估这个接收到的值,而外部 yield 立即产生该值。


每个 yield 在概念上都包含两个部分:

  1. sendnext 的调用者传递一个值。
  2. 从下一个 sendnext 调用接收值。

同样,每个sendnext 在概念上都有两部分:

  1. 将值传输到生成器当前暂停的 yield 表达式。 (对于 next,此值为 None。)
  2. 从下一个 yield 表达式接收一个值。

系统中最令人困惑的部分可能是这些部分是交错的。 yield 的两部分对应于 sendnext 的两个不同调用,send 的两部分> 或 next 对应于两个不同的 yield

如果我们研究一个简单的例子:

def gen():
print('Not ran at first')
yield (yield)

g = gen() # Step 1
print(next(g)) # Step 2
print(g.send(1)) # Step 3
g.send(2) # Step 4

事情是这样的:

Inside the generator                      Outside the generator

第一步

                                          g calls gen()
g returns a generator object
without executing the print
just yet statement.
>>> g
<generator object gen at 0x7efe286d54f8>

第 2 步

                                          next(g) sends None to g
g receives None, ignores it
(since it is paused at the start
of the function)

g prints ('not ran at first')

g executes the "transmit" phase
of the inner yield, transmitting
None
next(g) receives None

第 3 步

                                          g.send(1) sends 1 to g
g executes the "receive" phase
of the inner yield, receiving 1
g executes the "transmit" phase
of the outer yield, transmitting 1
g.send(1) receives 1 from g

第四步

                                          g.send(2) sends 2 to g
g executes the "receive" phase
of the outer yield, receiving 2
g reaches the end of gen and raises
a StopIteration
g.send(2) raises the StopIteration
from g

关于python - yield (yield) 有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45899681/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com