简体   繁体   中英

Issue calling a method on a parent class

I am new to Python classes and trying to understand the concept of inheritance. I have a class called Math which inherits from Calc . From Math.product() I am trying to invoke the base class method mul() as below:

class Calc(object):
    def mul(a, b):
        return a * b

class Math(Calc):
    def product(self, a, b):
        return super(Math, self).mul(a, b)

if __name__ == "__main__":  
    m = Math()
    print "Product:", m.product(1.3, 4.6)

When I run the code I'm getting the error below but as far as I can tell I have only passed two args for mul() within Math.product(a,b) . Can someone shed a light as to what mistake I have made?

Product:
Traceback (most recent call last):
File "inheritance.py", line 14, in <module>
print "Product:", m.product(1.3, 4.6)
File "inheritance.py", line 9, in product
return super(Math, self).mul(a, b)
TypeError: mul() takes exactly 2 arguments (3 given)

You need to include self as a parameter in

class Calc(object):
    def mul(a, b):
        return a * b

Either that or use the staticmethod decorator.

For example:

class Calc(object):
    @staticmethod
    def mul(a, b):
        return a * b

Right now when you call super(Math, self).mul(a, b) It passes in the following arguments in order, self, a, b . Any time you call a method on a class (dot method), it implicitly passes self as the first parameter.

The staticmethod decorator tells the function that it doesn't operate on a specific instance of the class, so there's no need to pass in self .

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