[Tutor] Modify inherited methods

Alan Gauld alan.gauld at btinternet.com
Wed Apr 28 02:32:16 CEST 2010

"Steven D'Aprano" <steve at 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.

def __init__(....)
     # do local pre processing(optional)
     #  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 

> 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 :-)


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list