TypeError:必须使用calculadora实例作为第一个参数调用未绑定方法mult()(改为使用int实例)

时间:2016-11-19 05:21:31

标签: python python-2.7

我得到了 TypeError:必须使用calculadora实例作为第一个参数调用未绑定方法mult()(改为使用int实例)

运行我的python文件时:

    from __future__ import print_function

class calculadora:


    def suma(x,y):
        added = x + y
        print(added)

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

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


calculadora.mult(3,5)

1 个答案:

答案 0 :(得分:1)

如果要将方法作为静态方法访问(访问没有clas实例的方法),则需要使用@staticmethod来装饰它们:

class calculadora:
    @staticmethod
    def suma(x, y):
        added = x + y
        print(added)

    @staticmethod
    def resta(x, y):
        sub = x - y
        print(sub)

    @staticmethod
    def mult(x, y):
        multi = x * y
        print(multi)

如果您的意思是实例方法,则需要先创建实例。并需要修改方法'签名包括self作为第一个参数:

class calculadora:
    def suma(self, x, y): # not `self`, refering class instance
        added = x + y
        print(added)

    def resta(self, x, y):
        sub = x - y
        print(sub)

    def mult(self, x, y):
        multi = x * y
        print(multi)


c = calculadora()  # Create instance
c.mult(3,5)  # Access the method through instance, (not class)