"Steven D'Aprano" <st...@pearwood.info> wrote
On Wed, 28 Apr 2010 07:24:48 am C M Caine wrote:
I'm writing a class that inherits the inbuilt dict class and want
some of my own code to run at initialisation, on the other hand, I
still want the original dict.__init__ function to run. ...

This is the general technique for calling the superclass' method:

class MyDict(dict):
   def __init__(self, *args, **kwargs):
       # Call the superclass method.
       dict.__init__(self, *args, **kwargs)
       # Perform my own initialisation code.
       print "Calling my init code..."

And just to be clear that applies to any method not just __init__
Also you can do your intialisation before or after or both.
eg.

def __init__(....)
    # do local pre processing(optional)
    super(....).__init__(...)
    #  do local post processing(optional)

Some people argue that you must call dict.__init__ even though it doesn't do anything. Their reasoning is, some day its behaviour might change, and if you don't call it in your subclass, then your class may break.

I tend to argue for calling even if its a null call. Mainly because you sometimes don't know what the superclass does or doesn't do (eg you might not have access to the source) so its safer to call it...

the behaviour of dict.__init__ changes, and you *do* call it, your class may still break.

... and if it breaks you at least have access to your own code to fix it...

But if you do have access to the superclass source then you can make an informed decision. In general I'm too lazy to go looking for it and just put the super call in :-)

HTH,


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

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to