I need to write handlers for several different case types (in Python). The interface for all this types are the same, but the handling logic is different.
One option would be defining a common class that receives the particular handler type as one of the __init__ parameters:
class Handler:
def __init__ (self, handlerType):
self._handlerType = handlerType
self._handler = handlerType.handleStuff
def handleStuff(self, *args, **kwargs):
return self._handler(args, kwargs)
# case specific handlers
class Handler_Case1:
def handleStuff(self, *args, **kwargs):
print 'Handling Case 1'
class Handler_Case2:
def handleStuff(self, *args, **kwargs):
print 'Handling Case 2'
if __name__ == '__main__':
handlers = []
handlers.append(Handler(Handler_Case1))
handlers.append(Handler(Handler_Case2))
for h in handlers:
h.handleStuff()
However, this results in a TypeError:
TypeError: unbound method handleStuff() must be called with Handler_Case1 instance as first argument (got tuple instance instead)
Another option is to mimic abstract function, as shown here("Q: Can you implement abstract classes in Python in 0 lines of code?"):
class Handler:
def handleStuff(self, *args, **kwargs): abstract
def commonFunction(self):
print 'Common function'
# case specific handlers
class Handler_Case1(Handler):
def handleStuff(self, *args, **kwargs):
print 'Handling Case 1'
class Handler_Case2(Handler):
def handleStuff(self, *args, **kwargs):
print 'Handling Case 2'
if __name__ == '__main__':
handlers = []
h1 = (Handler_Case1())
h2 = (Handler_Case2())
handlers.append(h1)
handlers.append(h2)
for h in handlers:
h.handleStuff()
print
So, actually, I have two questions:
- Which of the two approaches is more pythonic? and
- How to implement the first one?