B
Bruno Desthuilliers
Ratko a écrit :
s/is/is not/, of course
Hem... Almost !-)
Yeps - a placeholder 'abstract' method with only a docstring. It's a
common pattern in frameworks, but usually it's just an ordinary template
method pattern defaulting to a no-op.
FWIW, if you have several such methods to handle, you can use a more
generic approach:
_handlers = {
'onKey':registerForKeyEvents,
'onClick':registerForMouseEvents,
} # etc
class EventHandler(object):
for _name in _handlers:
exec "%s=lambda self, *args, **kw: pass" % _name
def __new__(cls, *args, **kw):
obj = object.__new__(cls, *args, **kw)
for name, register_func in _handlers.items():
meth = getattr(obj, name)
dummy = getattr(EventHandler, name)
if meth.im_func is not dummy.im_func:
register_func(meth)
return obj
HTH
> bruno a écrit
s/is/is not/, of course
The second solution works beautifully!
Hem... Almost !-)
Thank you very much.
I was aware that not implementing the onKey method in the first place
is the simplest solution but it's much cleaner to offer the methods in
advance so that the user can see what is possible.
Yeps - a placeholder 'abstract' method with only a docstring. It's a
common pattern in frameworks, but usually it's just an ordinary template
method pattern defaulting to a no-op.
FWIW, if you have several such methods to handle, you can use a more
generic approach:
_handlers = {
'onKey':registerForKeyEvents,
'onClick':registerForMouseEvents,
} # etc
class EventHandler(object):
for _name in _handlers:
exec "%s=lambda self, *args, **kw: pass" % _name
def __new__(cls, *args, **kw):
obj = object.__new__(cls, *args, **kw)
for name, register_func in _handlers.items():
meth = getattr(obj, name)
dummy = getattr(EventHandler, name)
if meth.im_func is not dummy.im_func:
register_func(meth)
return obj
HTH