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

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Sep 24 11:32:58 EDT 2007


Ratko a écrit :
> Hi all,
> 
> I was wondering if something like this is possible. Can a base class
> somehow know if a certain method has been overridden by the subclass?

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, ie:


class Parent(object):
   def method(self):
     raise NotImplementedError

class GoodGirl(Parent):
   def method(self):
     print "I'm a good girl"

class BadBoy(Parent):
   pass


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)..

HTH



More information about the Python-list mailing list