[Tutor] inheritance

alan.gauld@bt.com alan.gauld@bt.com
Wed Nov 13 07:16:01 2002


> class blah:
>     def __init__(self,blah, blah, blah):
>     def method(self,yak,yak,yak):
      def method2(self,fooby):

> class thbbt(blah):
>     def __init__(self,la,la,la):
>     def method(self,yakkity,yak):
> 
> My question then is this:  when I call thbbt.__init__ or 
> thbbt.method, what happens?  

You call the method you defined in thbbt.

If you call thbbt.method2(), which is only defined in blah then
python looks first in thbbt and can't find it. It then looks at 
each parent class in order(if there are more than one!) until 
it finds the first method called method2().

If you want access to the blah method() when you call thbbt.mathod()
then you must explicily call the parent mathod:

class thbbt(blah):
   def method(self,yakkity):
      blah.method(self,yakkity, 42, 65)
      # now do my bits here

There are three common uses for this technique:
1/ First to exted an inheritred method as I did above.

2/ Second to change the pre method state before calling the inherited
method:

class thbbt(blah):
   def method(self,yakkity):
      # change state values here - internal class variables etc
      # now call inherited method using new state
      blah.method(self,yakkity, 42, 65)
      

3/ Combine the two to change state and then process the resultant 
   state some more:

class thbbt(blah):
   def method(self,yakkity):
      # change state here
      blah.method(self,yakkity, 42, 65)
      # now do my bits with new state

The final option in overridding an inherited method is to ignore 
the inherited functionality and replace it completely.

To summarise then:
Python looks for the method called first in the current class then 
in each of the parent classes in turn. It calls the first one it 
finds and stops searching after that.

If you override an existing parent method you must decide whether 
to replace it entirely (unusual!) or explicitly call it using the 
class name and explicitly passing self.

HTH,

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld