16

It baffles me how I can't find a clear explanation of this anywhere. Why and when do you need to call the method of the base class inside the same-name method of the child class?

class Child(Base):
    def __init__(self):
        Base.__init__(self)

    def somefunc(self):
        Base.somefunc(self)

I'm guessing you do this when you don't want to completely overwrite the method in the base class. is that really all there is to it?

user1369281
  • 161
  • 1
  • 1
  • 3

2 Answers2

13

Usually, you do this when you want to extend the functionality by modifiying, but not completely replacing a base class method. defaultdict is a good example of this:

class DefaultDict(dict):
    def __init__(self, default):
        self.default = default
        dict.__init__(self)

    def __getitem__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            result = self[key] = self.default()
            return result

Note that the appropriate way to do this is to use super instead of directly calling the base class. Like so:

class BlahBlah(someObject, someOtherObject):
    def __init__(self, *args, **kwargs):
        #do custom stuff
        super(BlahBlah, self).__init__(*args, **kwargs) # now call the parent class(es)
Community
  • 1
  • 1
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
  • What's so great about this "super" functions? – user1369281 May 02 '12 at 06:41
  • 5
    @user1369281: Well, they're not always great. If you use them consistently however, they make inheritance trees much easier to work with. What if, for example, I wanted to change my `defaultdict` to a default _ordered_ dict. If I used `super()`, the _only_ thing I would have to change in my code would be the class definition. All those `super`'s automatically refer to whatever base class my current class is inheriting from. It facilitates black box programming. – Joel Cornett May 02 '12 at 06:48
  • I like this because it reminds you (or teaches) that your class can inherit multiple classes. So if your parent class is from a lib you can't modify and doesn't inherit object already, you can just add `object` to your class. – casey Nov 07 '13 at 23:29
2

It completely depends on the class and method.

If you just want to do something before/after the base method runs or call it with different arguments, you obviously call the base method in your subclass' method.

If you want to replace the whole method, you obviously do not call it.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636