Can a base class know if a method has been overridden?

Ratko rjagodic at gmail.com
Mon Sep 24 15:13:05 EDT 2007


> Ok. The simplest solution, then, is simply to not implement the method
> in the base class, ie:
>
> class EvtHandler:
>      def __init__(self):
>          if hasattr(self, 'onKey'):
>               register_for_key_events()
>
>       #def onKey(self):
>       #    pass
>
> class MyHandler(EvtHandler):
>      def onKey(self):
>          # do something here....
>
> Another solution is to compare the functions wrapped by the methods:
>
> class EvtHandler:
>      def __init__(self):
>          onKey = getattr(self, 'onKey')
>          if onKey.im_func is EvtHandler.onKey.im_func:
>               register_for_key_events()
>
>       def onKey(self):
>          pass
>
> class MyHandler(EvtHandler):
>      def onKey(self):
>          # do something here....
>
> HTH

The second solution works beautifully! 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.

Ratko




More information about the Python-list mailing list