为什么收益率可​​以指数化?

Why can yield be indexed?

我认为我可以通过直接访问通过 send 传递给生成器的值的索引来简化我的 python (2.7.10) 代码,并且对代码 运行.然后我发现应用于 yield 的索引实际上没有做任何事情,也没有抛出异常:

def gen1():
    t = yield[0]
    assert t
    yield False

g = gen1()
next(g)
g.send('char_str')

但是,如果我尝试索引 yield 三次或更多次,则会出现异常:

def gen1():
    t = yield[0][0][0]
    assert t
    yield False

g = gen1()
next(g)
g.send('char_str')

抛出

TypeError: 'int' object has no attribute '__getitem__'

这是异常不一致的行为,我想知道是否有一个直观的解释来解释索引收益率的实际作用?

您没有编制索引。您正在提供一份清单;表达式 yield[0] 实际上与以下内容相同(但没有变量):

lst = [0]
yield lst

如果您查看 next() 返回的内容,您会得到该列表:

>>> def gen1():
...   t = yield[0]
...   assert t
...   yield False
...
>>> g = gen1()
>>> next(g)
[0]

没有yield[0]之间有一个space,仅此而已。

异常是由于您尝试将订阅应用于包含的 0 整数:

>>> [0]        # list with one element, the int value 0
[0]
>>> [0][0]     # indexing the first element, so 0
0
>>> [0][0][0]  # trying to index the 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable

如果要索引发送到生成器的值,请在 yield 表达式两边加上括号:

t = (yield)[0]

演示:

>>> def gen1():
...     t = (yield)[0]
...     print 'Received: {!r}'.format(t)
...     yield False
...
>>> g = gen1()
>>> next(g)
>>> g.send('foo')
Received: 'f'
False