Can a base class know if a method has been overridden?
Ratko
rjagodic at gmail.com
Mon Sep 24 11:48:07 EDT 2007
> If your use case is to make sure a given ('abstract') method has been
> overriden, the canonical solution is to raise NotImplementedError in the
> base class's implementation
I am not really interested in forcing the subclass to implement a
method. I am interested in knowing *whether* it did implement it or
not.
> Else, this may be possible using a custom metaclass (or possibly just
> specializing the __new__ method), but there may be better solutions
> (depending on what you're really trying to do)..
I have a base class EvtHandler that has methods defined to handle
certain events. You then subclass from EvtHandler and override the
methods for the events you want to receive. If a method has been
overridden, the base class will automatically register for those
events to make sure that they are even delivered to this handler
(which is why I would need to know whether a method has been
overridden or not). Of course, there are other ways of doing this
which would require a bit more work from the subclass... I just
thought this would be a neat "automatic" way of registering for
events.
For example:
class EvtHandler:
def __init__(self):
if onKey is overridden:
register_for_key_events()
def onKey(self):
pass
class MyHandler(EvtHandler):
def onKey(self):
# do something here....
More information about the Python-list
mailing list