Python 调用父类上的方法时出现问题

Python 调用父类上的方法时出现问题,python,inheritance,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__ == "__mai

我不熟悉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)
当我运行代码时,我得到了下面的错误,但据我所知,我在Math.producta,b中只传递了mul的两个参数。有人能解释一下我犯了什么错误吗

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)
您需要将self作为参数包含在

class Calc(object):
    def mul(a, b):
        return a * b
或者使用staticmethoddecorator

例如:

class Calc(object):
    @staticmethod
    def mul(a, b):
        return a * b
现在,当你调用superMath,self.mula,b时,它会按顺序传递以下参数,self,a,b。无论何时调用类dot方法上的方法,它都会隐式传递self作为第一个参数


staticmethod decorator告诉函数它不在类的特定实例上操作,因此不需要传入self。

这些都不需要在类中,您只需从操作符import mul开始,就可以使用它!太酷了。。这两种解决办法都很有效@我想staticmethod decorator是实现这一点的最首选方法,是吗?是的,如果函数不使用它所调用的类的任何属性,staticmethod会使它最具可读性。我喜欢htis作为答案,OP也会这样做:Awsome。。。但是我希望附加到类Calc的名称空间或连接到类Calc的名称空间的方法mul有一些更具体的东西,这些东西已经被编辑掉了,否则我会用@jornsharpe的评论来回答这个问题-@我同意。问题提到OP这样做是为了学习继承,否则我只会提出Jon Sharpe的建议。要么是这样,要么就是把这个方法从课堂上拉出来。@MorganThrapp:正如我所写的,我是认真的:这个可怕的声音很大,而这个声音很安静;-当我上一次进入一个新的编码团队时,我被散布在所有类上的装饰淹没了,这让设计与@classmethod和@staticmethod之间的不匹配令人恐惧。输入的足够多,会投票。。。