TypeError:在Python 2中,必须以实例作为第一个参数(而不是int实例)调用未绑定方法

Ars*_*van 2 python python-2.7

在python 3中,以下代码集有效,我想知道为什么在python 2.7中它给我TypeError:必须以calc实例作为第一个参数(而不是int实例)调用未绑定方法add()?如何在Python 2.7中解决此问题?

class calc:
    def add(x,y):
        answer = x + y
        print(answer)

    def sub(x,y):
        answer = x - y
        print(answer)

    def mult(x,y):
        answer = x * y
        print(answer)

    def div(x,y):
        answer = x / y
        print(answer)

calc.add(5, 7)
Run Code Online (Sandbox Code Playgroud)

Kir*_*hou 5

使用staticmethod你的情况为python2.7

class calc:

    @staticmethod
    def add(x,y):
        answer = x + y
        print(answer)

#call staticmethod add directly 
#without declaring instance and accessing class variables
calc.add(5,7)
Run Code Online (Sandbox Code Playgroud)

或者,instance method如果需要调用其他实例方法或在类中使用任何东西,请使用

class calc:

    def add(self,x,y):
        print(self._add(x,y)) #call another instance method _add
    def _add(self,x,y):
        return x+y

#declare instance
c = calc()
#call instance method add
c.add(5,7) 
Run Code Online (Sandbox Code Playgroud)

此外,classmethod如果需要使用类变量但不声明实例,请使用

class calc:

    some_val = 1

    @classmethod
    def add_plus_one(cls,x,y):
        answer = x + y + cls.some_val #access class variable
        print(answer)

#call classmethod add_plus_one dircetly
#without declaring instance but accessing class variables
calc.add_plus_one(5,7)
Run Code Online (Sandbox Code Playgroud)