fork download
  1. from functools import partial
  2.  
  3. class DispatchError(Exception):
  4. pass
  5.  
  6. class Dispatcher:
  7. def __init__(self, prefix='on_'):
  8. self._prefix = prefix
  9.  
  10. def on_default(self, method, *args, **kw):
  11. raise DispatchError('"{}" undefined.'.format(method))
  12.  
  13. def __call__(self, method, *args, **kw):
  14. return getattr(
  15. self,
  16. self._prefix + method,
  17. partial(self.on_default, method)
  18. )(*args, **kw)
  19.  
  20. class ActorDispatcher(Dispatcher):
  21. def on_move(self, *args, **kw):
  22. print('moving...')
  23. def on_attack(self, *args, **kw):
  24. print('attacking..')
  25. # etc...
  26.  
  27. print( list( map(
  28. ActorDispatcher(), ['move', 'attack'] * 2
  29. )))
Success #stdin #stdout 0.03s 9440KB
stdin
Standard input is empty
stdout
moving...
attacking..
moving...
attacking..
[None, None, None, None]