can a subclass method determine if called by superclass?

Jean-Michel Pichavant jeanmichel at
Thu Jan 5 06:13:39 EST 2012

Jean-Michel Pichavant wrote:
> Peter wrote:
>> Situation: I am subclassing a class which has methods that call other
>> class methods (and without reading the code of the superclass I am
>> discovering these by trial and error as I build the subclass - this is
>> probably why I may have approached the problem from the wrong
>> viewpoint :-)).
>> Problem: when overriding one of these "indirectly called" superclass
>> methods I would like to take differing actions (in the subclass
>> instance) depending on whether it is the superclass or the subclass
>> instance performing the call.
>> Question: Is there any way to determine in a method whether it is
>> being called by the superclass or by a method of the subclass
>> instance?
>> Now I suspect that what I am doing is actually very muddy thinking :-)
>> and I don't want to attempt to explain why I am approaching the design
>> this way as an explanation would require too much work - I will
>> consider an alternative inheritance approach while waiting an answer,
>> but the answer to the question interested me (even if I do a redesign
>> and come up with a more "elegant" approach to the problem).
>> Thanks
>> Peter
> As you suspected, this is probably the wrong approach.
> However since you asked for a solution anyway :o)
> class Parent(object):
>  def foo(self):
>    # implementation by subclasses is still REQUIRED
>    if self.__class__ is Parent:
>       raise NotImplementedError()
>    # common code for all foo methods
>    print "calling foo"
> class Child(Parent):
>  def foo(self):
>    # You can still call the virtual method which contains some code    
>    # here the custom code
> p = Parent()
> c = Child()
> Note that this is not the best approach, still acceptable because 
> there is no code specific to a subclass in the base class.
> JM
I just realized I didn't addressed the problem you described, sorry, 
just ignore my mail.


More information about the Python-list mailing list