Is Python idiomatic using an abstract class for event handler callbacks?

I am creating an event manager structure that decrypts messages and accesses custom code. My C ++ background suggests that I write:

class Handler:
    def onFoo(self):
        pass
    def onBar(self):
        pass

class Dispatcher:
    def __init__(self):
        self.handler = Handler()

    def run():
        while True:
            msg = decode_message() # magic
            if msg == 'foo':
                handler.onFoo()
            if msg == 'bar':
                handler.onBar()

Then the framework user should write something like:

class MyHandler(Handler):
    def onFoo(self):
        do_something()

dispatcher = Dispatcher()
myHandler = MyHandler()
dispatcher.handler = myHandler
dispatcher.run()

But I can also imagine that the put onFoo()and onBar()as methods Dispatcherand allow the user to replace them with other methods. Then the user code will look like this:

def onFoo():
    do_something()

dispatcher = Dispatcher()
dispatcher.onFoo = onFoo

I could also make a Dispatcher.onFoolist of calls so that the user can attach more than one handler, for example, in C #.

What is the most pythonic way to do this?

+5
source share
1 answer

, - , , , Dispatcher (.. Handler ), Handler .

, Handler ; Handler , - . , , Handler. Handler - Handler. , no-op placeholder, .

, , ; , "pythonic", , Handler Dispatcher. ( , , threading.Thread, - , .)

, , bonafide, ! 2.6, Python . , abstractmethod, , ; , . ++, , , - , , , , .

+4

All Articles