【问题标题】:How to persist the state of python generators between event callbacks如何在事件回调之间保持python生成器的状态
【发布时间】:2013-12-09 01:50:06
【问题描述】:

所以我正在尝试学习 leap-motion SDK 并在 4 到 5 年没有接触它之后重新学习 python,我在 python 2.7 中遇到了生成器的问题

基本上我有一个单词列表,每次跳跃动作选择一个新的“圆圈”手势时,我想打印列表中的下一个单词。我所看到的是,每次on_frame 回调触发时,只会打印列表中的第一个单词。我相信正在发生的事情是 python 运行时忘记了事件之间生成器的状态。有没有办法在手势事件之间保持生成器状态?

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

对此的任何见解都会很棒。谢谢

【问题讨论】:

    标签: python python-2.7 generator leap-motion


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      而是每一个最​​多创建一次

      clockwise = GestureActions.clockwiseCircleGesture()
      counter_clockwise = GestureActions.counterClockwiseCircleGesture()
      # then
      
      action = clockwise if foo else counter_clockwise
      
      action.next()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-18
        • 1970-01-01
        相关资源
        最近更新 更多