Ratko a écrit : >> 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.... >
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 -- http://mail.python.org/mailman/listinfo/python-list