Last active
August 29, 2015 14:02
-
-
Save Ikke/f071c1f9a910ae81b612 to your computer and use it in GitHub Desktop.
OOP Statemachine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Context(): | |
def __init__(self): | |
self.result = [] | |
self.current = {} | |
self.lastValue = 0 | |
def setBeginValue(self, value): | |
self.current['beginValue'] = value | |
def buildResult(self): | |
if self.current: | |
self.current['endValue'] = self.lastValue | |
self.result.append(self.current) | |
self.current = {} | |
class StateMachine(): | |
def __init__(self): | |
self.state = BeginState | |
self.context = Context() | |
def __getattr__(self, attr): | |
if attr in ['begin', 'middle', 'end']: | |
method = getattr(self.state, attr) | |
def caller(*args, **kwargs): | |
self.state = method(self.context, *args, **kwargs) | |
self.context.lastValue = args[0] | |
return caller | |
else: | |
raise AttributeError(attr) | |
def result(self): | |
if self.state == EndState: | |
self.context.buildResult() | |
return self.context.result | |
class State(): | |
@classmethod | |
def begin(cls, context, index, value): | |
return cls | |
@classmethod | |
def middle(cls, context, index, value): | |
return cls | |
@classmethod | |
def end(cls, context, index, value): | |
return cls | |
class BeginState(State): | |
@classmethod | |
def begin(cls, context, index, value): | |
context.setBeginValue(index) | |
return MiddleState | |
class MiddleState(State): | |
@classmethod | |
def end(cls, context, index, value): | |
return EndState | |
class EndState(State): | |
@classmethod | |
def begin(cls, context, index, value): | |
context.buildResult() | |
return BeginState.begin(context, index, value) | |
@classmethod | |
def middle(cls, context, index, value): | |
context.buildResult() | |
return BeginState | |
machine = StateMachine() | |
mapping = { | |
1: "begin", | |
0: "middle", | |
-1: "end" | |
} | |
for index, value in enumerate(lst): | |
method_name = mapping[value] | |
method = getattr(machine, method_name) | |
method(index, value) | |
from pprint import pprint | |
pprint(machine.result()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment