gpt4 book ai didi

python-3.x - 使用 next(gen) 和 gen.send(None) 启动 Python 3 生成器有区别吗?

转载 作者:行者123 更新时间:2023-12-03 16:54:33 25 4
gpt4 key购买 nike

当您创建 Python 3 生成器并立即开始运行它时。您会收到如下错误:

TypeError: can't send non-None value to a just-started generator

为了去(向它发送消息或从它获取某些东西),您首先必须调用 __next__上面: next(gen)或将 None 传递给它 gen.send(None) .

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

# gen is a <generator object echo_back at 0x103cc9240>
gen = echo_back()

# send anything that is not None and you get error below
# this is expected though
gen.send(1)

# TypeError: can't send non-None value to a just-started generator

# Either of the lines below will "put the generator in an active state"
# Don't need to use both
next(gen)
gen.send(None)

gen.send('Hello Stack Overflow')

# Prints: Hello Stack Overflow)

两种方式产生相同的结果(启动发电机)。

next(gen) 启动发电机有什么区别(如果有的话)而不是 gen.send(None) ?

最佳答案

来自 generator.send() :

When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value.



调用 next()在生成器上开始执行,直到第一个 yieldNone的表达式可以将值发送到其中,这将成为 yield 的值表达式(例如, x = yield)。

两个 next(gen)gen.send(None)行为相同(即用法没有区别)。

关于python-3.x - 使用 next(gen) 和 gen.send(None) 启动 Python 3 生成器有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29907057/

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