您可能正在寻找的是send
允许将值发送到生成器的方法。该参考提供了一个示例:
>>> def echo(value=None):
... print "Execution starts when 'next()' is called for the first time."
... try:
... while True:
... try:
... value = (yield value)
... except Exception, e:
... value = e
... finally:
... print "Don't forget to clean up when 'close()' is called."
...
>>> generator = echo(1)
>>> print generator.next()
Execution starts when 'next()' is called for the first time.
1
>>> print generator.next()
None
>>> print generator.send(2)
2
>>> generator.throw(TypeError, "spam")
TypeError('spam',)
>>> generator.close()
Don't forget to clean up when 'close()' is called.
让我举一个我自己的例子。(注意!上面的代码是 Python 2.6,但下面我会写 Python 3;py3k ref):
>>> def amplify(iter, amp=1):
... for i in iter:
... reply = (yield i * amp)
... amp = reply if reply != None else amp
...
>>> it = amplify(range(10))
>>> next(it)
0
>>> next(it)
1
>>> it.send(3) # 2 * 3 = 6
6
>>> it.send(8) # 3 * 8 = 24
24
>>> next(it) # 4 * 8 = 32
32
当然,如果你真的想要,你也可以不用send
. 例如,通过将生成器封装在一个类中(但它几乎没有那么优雅!):
>>> class MyIter:
... def __init__(self, iter, amp=1):
... self.iter = iter
... self.amp = amp
... def __iter__(self):
... for i in self.iter:
... yield i * self.amp
... def __call__(self):
... return iter(self)
...
>>> iterable = MyIter(range(10))
>>> iterator = iterable()
>>> next(iterator)
0
>>> next(iterator)
1
>>> iterable.amp = 3
>>> next(iterator)
6
>>> iterable.amp = 8
>>> next(iterator)
24
>>> next(iterator)
32
更新:好的,既然你已经更新了你的问题,让我再试一试这个问题。也许这就是你的意思?
>>> def amplify(iter, loc={}):
... for i in iter:
... yield i * loc.get('amp', 1)
...
>>> it = amplify(range(10), locals())
>>> next(it)
0
>>> next(it)
1
>>> amp = 3
>>> next(it)
6
>>> amp = 8
>>> next(it)
24
>>> next(it)
32
请注意,locals()
应将其视为只读并且取决于范围。如您所见,您需要显式传递locals()
给生成器。我看不出有什么办法...