[Tutor] Calling method in parent class

Alan Gauld alan.gauld at btinternet.com
Tue May 12 18:37:05 CEST 2009


"Jeremiah Dodds" <jeremiah.dodds at gmail.com> wrote

> Can you give a concrete example of _why_ you would want to do this? You 
> can
> use super, if you really want to, but it can get ugly (I do not fully
> understand all of supers caveats). I can't think of a case off the top of 
> my
> head where you would want to call a parent class's method that a child
> instance has overriden, but I'm sure it happens sometimes.

Actually I'd say this was the normal case in good OO programming.
You should program the differences so that mostly you are writing either
some extra initialisation or some local post processing with the bulk
of the code in the base class.

__init__ is the obvious case where you simply call the base class
to initialise the inherited attributes then add on the local attributes
in the child class. This ripples all the way up the inheritance chain.

Another similar case is where you are serialising an object. The
child class calls the parent class to serialise all of the inherited
stuff and then tags on the child features at the end. To deserialize
simply reverse the process.

Lisp makes this explicit by having before and after methods which
are automatically called. Thus for method foo the order is

before_foo()     # ripples up the tree calling all the precondition code
foo()                  # executes all the core code, usually only in 1 or 2 
classes
after_foo()        # ripples up tree calling all the post condition code

We can fake this in other languages with a naming convention
such as the one above but we still need to do a fair bit of explicit
coding. Lisp does it automagically. (You might be able to do
something like it in Python using decorators....hmmmm.)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list