[Tutor] Modify inherited methods

Steven D'Aprano steve at pearwood.info
Wed Apr 28 00:08:12 CEST 2010


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. Can I ask the
> class to run the original __init__ and then my own function at
> initialisation automatically? If so, how?

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..."


For advanced usage, replace the call to dict.__init__ with a call to 
super:

        super(MyDict, self).__init__(*args, **kwargs)

And for guru-level mastery, replace to call to dict.__init__ with ... 
nothing at all, because dict.__init__ doesn't do anything.

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. This is true, as far as it goes, but what they say is that if 
the behaviour of dict.__init__ changes, and you *do* call it, your 
class may still break. (This is why dict is unlikely to change any time 
soon.)




-- 
Steven D'Aprano


More information about the Tutor mailing list