简体   繁体   中英

Error by using super().Sub(n1,n2) in python

I have this code:

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()

But when I run it I got an error:

> 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

And when I put the mouse at the super() function it tell's me

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

So what is the correct syntax to use super() here?

In Python 2.7, you have to write it like this:

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

Please refer to super() 's Python 2.7 documentation for more details.

In Python 2 to use super , you have to use new-style classes:

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

class OperationWithMul(Operation):
    # your code

# ...

And you have to pass in the current class and the instance explicitly to super :

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

In Python 3 you won't have these problems because all classes are new-style and super infers the needed arguments. Even though it's probably beyond the scope of the question, you should really consider switching to Python 3.

Also method names in Python typically start with a lower-case letter. That's not a hard rule but it could make your code easier to understand for other Python programmers (like myself).

This question seems to be similar to this one . In Python 2.7 the function call to super needs the following arguments:

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

And your root class needs to inherit from the object class:

class Operation(object):

In doing so, you define your class as a new-style class, which is the standard for Python 3.0 and comes with a range of advantages.

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