Aug-14-2019, 07:05 AM
(This post was last modified: Aug-14-2019, 07:06 AM by Gribouillis.)
Skaperen Wrote:every command involves accessing and modifying local variablesMake these variables members of a class instance and dispatch things on instance methods.
class CommandHandler: dispatch = { 'spam': 'on_spam', 'eggs': 'on_eggs', } def __init__(self, ...): self.foo = ... self.bar = ... def __call__(self, msg): getattr(self, self.dispatch[msg[0]])() def on_spam(self): self.foo = 3452 def on_eggs(self): self.foo = 1233Instance variables are the normal way to share data between several functions.
You can also use new classes to manage individual commands
class Command: def __init__(self, handler): self.handler = handler class Spam(Command): def run(self): self.handler.foo = 1023 class Eggs(Command): def run(self): self.handler.foo = 1048 class CommandHandler: dispatch = { 'spam': Spam, 'eggs': Eggs, } def __init__(self, ...): self.foo = ... self.bar = ... def __call__(self, msg): self.dispatch[msg[0]](self).run()