Python生成器行为

时间:2013-08-04 04:19:42

标签: python generator coroutine

我对发电机的误解是什么,我没有得到我期望的输出?我正在尝试创建一个简单的函数,它将输出任何数据i .send()它,或者如果没有信息发送则返回'none'。

import pudb
#pudb.set_trace()
def gen():
        i = 0
        while True:
                val = (yield i)
                i = val
                if val is not None:
                        yield val
                else:
                        yield 'none'

test = gen()
next(test)
print test.send('this')
print test.send('that')
print test.next()
print test.send('now')

预期产出:

'this'
'that'
'none'
'now'

实际输出:

'this'
'this'
'none'
'none'

1 个答案:

答案 0 :(得分:0)

您每次产生两次值。来到这里:

val = (yield i)

并且在这里:

yield val

您应该只生成一次每个值,并捕获用户的输入,如下所示:

def parrot():
    val = None
    while True:
        val = yield val

如果你真的想在用户调用'none'时产生字符串None而不是实际的next对象,那么你可以这样做,但这可能是一个坏主意:< / p>

def parrot():
    val = None
    while True:
        val = yield ('none' if val is None else val)
相关问题