通过在python中使用super()。Sub(n1,n2)出错

时间:2018-07-13 13:22:54

标签: python python-2.7 inheritance super

我有此代码:

class Operation:
    def Sum(self,n1,n2):
        SumResult=n1+n2
        print("Sum=",SumResult)
    def Sub(self,n1,n2):
        SubResult=n1-n2
        print("Sub=",SubResult)

class OperationWithMul(Operation):
    def Mul(self,n1,n2):
        MulResult=n1*n2
        print("Mul=",MulResult)
    def Sub(self,n1,n2):
        super().Sub(n1,n2)

def main():
    OpMul=OperationWithMul();
    OpMul.Sub(4,2)
    OpMul.Sum(10,15)
    OpMul.Mul(10,2)

if __name__ == '__main__':
    main()

但是当我运行它时,我得到了一个错误:

> Traceback (most recent call last):   File
> "C:/path/OOPOverride.py", line
> 32, in <module>
>     if __name__ == '__main__':main()   File "C:/path/OOPOverride.py", line
> 24, in main
>     OpMul.Sub(4,2)   File "C:/path/OOPOverride.py", line
> 14, in Sub
>     super(Operation).Sub(n1,n2) TypeError: must be type, not classobj

当我将鼠标放在super()函数上时,它告诉我

> Python version 2.7 does not support this syntax. super() should have
> arguments in Python

那么在这里使用super()的正确语法是什么?

3 个答案:

答案 0 :(得分:0)

在Python 2.7中,您必须这样编写:

super(OperationWithMul, self).Sub(n1,n2)

有关更多详细信息,请参阅super()'s Python 2.7 documentation

答案 1 :(得分:0)

在Python 2中使用super,您必须使用新型类:

class Operation(object):  # makes the base-class a new-style class
    # your code

class OperationWithMul(Operation):
    # your code

# ...

您必须将当前类和实例显式传递给super

super(OperationWithMul, self).Sub(n1, n2)

在Python 3中,您不会遇到这些问题,因为所有类都是新样式,并且super会推断出所需的参数。即使可能不在问题范围内,您也应该真正考虑切换到Python 3。

Python中的方法名称通常以小写字母开头。这不是硬性规定,但是它可以使其他Python程序员(例如我自己)更容易理解您的代码。

答案 2 :(得分:0)

这个问题似乎与this one类似。在Python 2.7中,对super的函数调用需要以下参数:

super(OperationWithMul,self).Sub(n1,n2)

您的根类需要从对象类继承:

class Operation(object):

这样做,您可以将类定义为新型类,这是Python 3.0的标准,并具有一系列优点。