简体   繁体   中英

Calling function from the base class

I'm new to Python.

I have a class which has some common definitions which will be used across several other classes in a module. This is the current structure of my program.

 class A(object):

    def __init__(self, x, y):
        """Initialization method"""
        super(A, self).__init__()
        self.x = x
        self.y = y

    def function_1(self, ftype):
        <<<some steps>>>
        return abc

    def function_2(self, stype):
        <<<some steps>>>        
        return xyz

class B(A):
    def __init__(self, x, y, e_type):
        A.__init__(self, x, y)
        self.e_type = enablement_type

    def function_3(self, mtype):
        <<<some steps>>>
        **HERE I need to call the function1 and function2 of class A**

1: just calling the functions from base class as

   A.function1(self, ftype='new')
   A.function2(self, stype='new')

is the correct way? Pylint says all good when I did so.

2: Also, can you elaborate super in easy terms please

For ur 1st question: What you are doing is code reusability with inheritance concept.

Once u said 'class B(A)', all the members and functions of A are available in B for usage. Hence, u can directly call B function like below

self.function1(ftype='new')
self.function2(stype='new')

This is the typical way of accessing any function of a instance in Python. Whatever you mentioned in question is just access a static function in any other file. That is going to work anyway. But it has nothing to do with inheritance.

For your 2nd question: In case of inheritance, you can choose to completely redefine a generic reusable function from base class or extend some feature for a special case or just use as it is. In the case of extension of existing function, what you need to do is override the function you want to extend and it's body should call all base class function, then additional code. Here calling a base class function is done with super.function()

def function1(self, ftype):
    super.function1(self, ftype)
    # the new code specific to this class goes here

init () are special functions, called as constructor. The are called while instantiating the class like 'objInstance = B()' . Other functions are treated as explained above.

Hope it clarifies your doubts.

Normally, you would call inherited functions like this:

self.function1('new')
self.function2('new')

What you wrote will work, but requires you to identify the exact base class containing these methods. That is a complication, and a potential for errors, that can easily be avoided by letting inheritance do its job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM