gpt4 book ai didi

python - 使用生成器发送方法。仍在尝试理解发送方法和古怪的行为

转载 作者:太空狗 更新时间:2023-10-29 22:30:46 33 4
gpt4 key购买 nike

这是我为理解发送方法而写的一个小函数:

>>> def test():
... for x in xrange(10):
... res = yield
... yield res
>>> a = test()
>>> next(a)
>>> next(a)
>>> next(a)
>>> next(a)
>>> a.send(0)
Traceback (most recent call last):
<ipython-input-220-4abef3782000> in <module>()
StopIteration
>>> a = test()
>>> a.send(0)
Traceback (most recent call last):
<ipython-input-222-4abef3782000> in <module>()
TypeError: can't send non-None value to a just-started generator
>>> a.send(None)
>>> a.send(0)
0
>>> a.send(0)
>>> a.send(0)
0
>>> a.send(0)
>>> a.send(0)
0
>>> a.send(0)

为什么第一次报错?

>>> a.send(0)
StopIteration

为什么要求第一个 send() 为 None?与此错误一样:

>>> a.send(0)
Traceback (most recent call last):
<ipython-input-222-4abef3782000> in <module>()
TypeError: can't send non-None value to a just-started generator

然后第一个发送启动生成器(我不知道为什么)我发送一个“0”并打印它但是第二个 0 再次没有并恢复我发送的任何内容(此处为 0)

>>> a.send(None)
>>> a.send(0)
0
>>> a.send(0)
>>> a.send(0)
0
>>> a.send(0)
>>> a.send(0)
0

此链接帮助不大 Python 3: send method of generators

最佳答案

为什么要求第一个 send() 为 None?

您不能第一次发送()一个值,因为生成器直到您有 yield 语句的那一点才执行,所以与该值无关。

以下是 pep 中的相关段落,介绍了与生成器协同例程的特性 (http://www.python.org/dev/peps/pep-0342/):

Because generator-iterators begin execution at the top of thegenerator's function body, there is no yield expression to receivea value when the generator has just been created. Therefore,calling send() with a non-None argument is prohibited when thegenerator iterator has just started, and a TypeError is raised ifthis occurs (presumably due to a logic error of some kind). Thus,before you can communicate with a coroutine you must first callnext() or send(None) to advance its execution to the first yieldexpression

一个小的演练:

def coro():
print 'before yield'
a = yield 'the yield value'
b = yield a
print 'done!'
c=coro() # this does not execute the generator, only creates it

# If you use c.send('a value') here it could _not_ do anything with the value
# so it raises an TypeError! Remember, the generator was not executed yet,
# only created, it is like the execution is before the `print 'before yield'`

# This line could be `c.send(None)` too, the `None` needs to be explicit with
# the first use of `send()` to show that you know it is the first iteration
print next(c) # will print 'before yield' then 'the yield value' that was yield

print c.send('first value sent') # will print 'first value sent'

# will print 'done!'
# the string 'the second value sent' is sent but not used and StopIterating will be raised
print c.send('the second value sent')

print c.send('oops') # raises StopIterating

关于python - 使用生成器发送方法。仍在尝试理解发送方法和古怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19892204/

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