I'm interpreting commands from a wire protocol. I have a class that encapsulates the command structure with something basic like
class Command:
def __init__(self, commandType, body):
self.commandType = commandType
self.body = body
@classmethod
def decode(cls, someBytes):
return cls(commandType=someBytes[0], body=someBytes[1:])
def dispatch(self):
pass # but could magic happen here?
def command1(self):
print("command1 stuff goes down")
def command42(self):
print("command42 stuff goes down")
What I'd like to be able to do is to somehow link the different commandN methods with the commandType so they could run in the dispatch method. A very naive/inefficient of dispatch could look like:
def dispatch(self):
methodName = f'command{self.commandType}'
method = getattr(self, methodName, None)
if method is not None:
method(self)
But that only works as long as I name methods commandN. It would be nicer to use names that are monikers of what that command represents. That led me down the path of decorators. But a regular decorator wouldn't be enough, I would need a parameterized one. But after reading this question, I wasn't sure I wanted that. And some of the comments seemed to indicate it might be troublesome around instance methods.
Is there a different pattern that I'm missing that I can use to accomplish the association of instance methods with the different byte values?