首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在事件回调之间持久保存python生成器的状态

如何在事件回调之间持久保存python生成器的状态
EN

Stack Overflow用户
提问于 2013-12-09 01:50:06
回答 2查看 645关注 0票数 1

因此,我尝试学习跳跃运动SDK,并在4-5年内没有接触到它之后重新学习它,并且在python2.7中遇到了生成器的问题。

基本上,我有一个单词列表,我想打印在列表中的下一个单词,每次跳跃运动拿起一个新的‘圆圈’手势。我看到的是,每当on_frame回调触发时,列表中的第一个单词就会被打印出来。我相信发生的事情是,python运行时忘记了事件之间生成器的状态。在手势事件之间是否存在保持生成器状态的方式?

代码语言:javascript
运行
复制
if not frame.hands.is_empty:
        for gesture in frame.gestures():
            if gesture.type == Leap.Gesture.TYPE_CIRCLE:
                circle = CircleGesture(gesture)
                # Determine clock direction using the angle between the pointable and the circle normal
                action = None
                if circle.pointable.direction.angle_to(circle.normal) <= Leap.PI/4:
                    action = GestureActions.clockwiseCircleGesture()
                else:
                    action = GestureActions.counterClockwiseCircleGesture()

                print action.next()

  def clockwiseCircleGesture():
       words = ["You", "spin", "me", "right", "round", "baby", "right", "round", "like", "a", "record", "baby",                          "Right", "round", "round", "round", "You", "spin", "me", "right", "round", "baby", "Right", "round", "like", "a",
         "record", "baby", "Right", "round", "round", "round"]
      for word in words:
          yield word

任何对这件事的洞察力都会很好。谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-12-09 01:57:31

我怀疑每次触发事件时都会重置您的action变量。

在事件处理函数之外初始化生成器。看起来你可能想要两个,clockwise_actioncounterclockwise_action

票数 2
EN

Stack Overflow用户

发布于 2013-12-09 02:01:27

不熟悉python,但是当人们学习生成器/迭代器/枚举器/任何东西时,这是一个常见的问题。您每次都要通过循环重新创建迭代器,并丢失状态。

相反,最多只创建一次

代码语言:javascript
运行
复制
clockwise = GestureActions.clockwiseCircleGesture()
counter_clockwise = GestureActions.counterClockwiseCircleGesture()
# then

action = clockwise if foo else counter_clockwise

action.next()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20461772

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档