Python inheritance - calling base class methods inside child class?
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)
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.