-1

我们有这两个代码。第一个有效,第二个无效。我们已经注释了所有行,并且我们已经验证,在第二行中,代码可以正常工作,直到我们引入该行:

d = yield viztask.waitDraw()

在第二个中,它甚至没有 print "collision",这是第一行,即使在viztask.waitDraw()下面声明了。

工作版本:

ball.enable(viz.COLLIDE_NOTIFY)
def onCollide(e):
        print('collision')
        global count 
        count = count+1
        print(count)

viz.callback( viz.COLLIDE_BEGIN_EVENT, onCollide )

def testReactionTime(threadName):
    print 'boolTime: '
    print(boolTime)
    while boolTime:
        #Wait for next frame to be drawn to screen
        d = yield viztask.waitDraw()
        #Save display time
        displayTime = d.time
        #Wait for keyboard reaction
        d = yield viztask.waitMouseUp(viz.MOUSEBUTTON_LEFT)
        #Calculate reaction time
        reactionTime = d.time - displayTime
        print(reactionTime)

非工作版本:

ball.enable(viz.COLLIDE_NOTIFY)
def onCollide(e):
        print('collision')
        global count
        if e.obj2 == beginning:
            #Wait for next frame to be drawn to screen
            d = yield viztask.waitDraw()
            #Save display time
            displayTime = d.time
            #viztask.schedule( testReactionTime("h"))
            print('start time')
        elif e.obj2 == end:
            global reactionTime
            d = yield viztask.waitDraw()
            reactionTime = d.time - displayTime
            print("count = ")
            print(count)
            print("time = ")
            print(reactionTime)
        else:
            count = count+1
            print(count)
viz.callback( viz.COLLIDE_BEGIN_EVENT, onCollide )
4

1 回答 1

0

当你yield从它里面时,你变成onCollide了一个生成器,而不是一个标准的函数。这是一个演示差异的最小示例:

>>> def func():
    s = "foo"
    print(s)
    return s

>>> f = func()
foo # print
>>> f
'foo' # returned value
>>> def gen():
    """Identical to the above, but with 'yield' instead of 'return'."""
    s = "foo"
    print(s)
    yield s


>>> g = gen()
# nothing happens here
>>> g
<generator object gen at 0x02F1C648> # nothing yielded yet
>>> h = next(g)
foo # print
>>> h
'foo' # yielded value

调用生成器会设置它,但在你调用next(或以其他方式尝试迭代它)之前没有任何实际运行。您将不得不重构代码以避免将生成器用作回调函数。

于 2014-10-03T10:34:07.530 回答