Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inheritance - calling base class methods inside child class?

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?

like image 443
user1369281 Avatar asked May 02 '12 06:05

user1369281


People also ask

Can a child class call base class methods?

A child class can access the data members of its specific base class, i.e., variables and methods. Within this guide, we will be discussing different ways to execute or call the base call function in C++.

Can a parent class access child class methods Python?

This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.

Does child class inherit methods?

Child classes inherit the methods of the parent class it belongs to, so each child class can make use of those methods within programs.


2 Answers

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)
like image 92
Joel Cornett Avatar answered Sep 20 '22 06:09

Joel Cornett


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.

like image 34
ThiefMaster Avatar answered Sep 21 '22 06:09

ThiefMaster