发出在父类上调用方法的问题

Swa*_*r C 0 python inheritance

我是Python类的新手,并试图理解继承的概念.我有一个叫做Math继承自的类Calc.从Math.product()我试图调用基类方法mul()如下:

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)
Run Code Online (Sandbox Code Playgroud)

当我跑我得到下面的错误,但据我可以告诉我只通过了两项args作为代码mul()Math.product(a,b).有人能说清楚我犯了什么错误吗?

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)
Run Code Online (Sandbox Code Playgroud)

Mor*_*app 8

您需要包含self作为参数

class Calc(object):
    def mul(a, b):
        return a * b
Run Code Online (Sandbox Code Playgroud)

无论是那个还是使用staticmethod装饰器.

例如:

class Calc(object):
    @staticmethod
    def mul(a, b):
        return a * b
Run Code Online (Sandbox Code Playgroud)

现在当你调用super(Math, self).mul(a, b)它时按顺序传递以下参数,self, a, b.无论何时在类(点方法)上调用方法,它都会隐式传递self为第一个参数.

staticmethod装饰告诉它不会在类的特定实例操作功能,所以没有必要在传递self.