Can a base class know if a method has been overridden?
Chris Mellon
arkanes at gmail.com
Mon Sep 24 12:09:10 EDT 2007
On 9/24/07, Ratko <rjagodic at gmail.com> wrote:
> > 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....
Clumsy, but it seems to work. Using a sentinel value as Marc Rintsch
suggests might be better:
>>> class A(object):
... def vMethod(self, x):
... raise NotImplemented
... def is_implemented(self, method):
... if getattr(type(self), method.__name__).im_func is not
method.im_func:
... return True
... def otherMethod(self, x):
... raise NotImplemented
...
>>> class B(A):
... def vMethod(self, x):
... print x
...
>>> b = b()
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'B' object is not callable
>>> b = B()
>>> b.otherMethod(10)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 8, in otherMethod
TypeError: exceptions must be classes, instances, or strings
(deprecated), not NotImplementedType
>>> b.vMethod(10)
10
>>> b.is_implemented(A.vMethod)
True
>>> b.is_implemented(A.otherMethod)
>>>
(Note that I accidentally raised NotImplemented instead of
NotImplementedError, oops.)
More information about the Python-list
mailing list