Python Yield

since 2014-04-15

http://d.nishimotz.com/archives/1685

ジェネレータ式で状態遷移を書いてみる:

import unittest
 
class State:
    FIRST = 1
    SECOND = 2
    END = 3
 
class Event:
    DUMMY = 100
    GOTO_SECOND = 101
    GOTO_END = 102
 
def stateManagerGenerator():
    while True:
        ev, arg = (yield State.FIRST)
        if ev == Event.GOTO_SECOND:
            break
    while True:
        ev, arg = (yield State.SECOND)
        if ev == Event.GOTO_END:
            break
    while True:
        ev, arg = (yield State.END)
 
def makeStateManager():
    return stateManagerGenerator()
 
class StateManagerTests(unittest.TestCase):
 
    def test_transition(self):
        stateManager = makeStateManager()
        state = stateManager.send(None)
        self.assertEqual(state, State.FIRST)
        state = stateManager.send((Event.DUMMY, "dummyArg"))
        self.assertEqual(state, State.FIRST)
        state = stateManager.send((Event.GOTO_SECOND, "dummyArg"))
        self.assertEqual(state, State.SECOND)
        state = stateManager.send((Event.GOTO_END, "dummyArg"))
        self.assertEqual(state, State.END)
        state = stateManager.send((Event.DUMMY, "dummyArg"))
        self.assertEqual(state, State.END)
 
if __name__ == '__main__':
    unittest.main()

python_yield.txt · 最終更新: 2014/05/23 14:44 by Takuya Nishimoto
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0