【问题标题】:TypeError: unbound method must be called with instance as first argument (got int instance instead) in Python 2TypeError:必须在 Python 2 中使用实例作为第一个参数(改为获取 int 实例)调用未绑定的方法
【发布时间】:2017-04-03 17:23:52
【问题描述】:

在 python 3 中,以下代码集有效,我想知道为什么在 python 2.7 中它给了我一个 TypeError: unbound method add() must be called with calc instance as first argument(得到 int 实例)?如何在 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)

【问题讨论】:

  • 您没有显示所有代码。这在 Python 2.7 中运行得非常好。另外,您的错误是引用了您未显示的代码。
  • @idjaw,对不起!我现在已经解决了!欢呼
  • 下一个问题。您是否希望calc 中的那些方法成为实例方法?因为你现在没有这样对待他们。
  • @idjaw,是的,就是这个想法
  • 重述@idjaw 的问题——你为什么要在这里上课?这些方法都没有使用self,而您调用它的方式似乎不太可能……使用类而不是仅仅提供一堆模块级函数有什么好处?

标签: python python-2.7


【解决方案1】:

在您的情况下,将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)

或者,如果您需要调用其他实例方法或使用类中的任何内容,请使用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) 

另外,如果您需要使用类变量但不声明实例,请使用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)

【讨论】:

    【解决方案2】:

    看起来就像你试图用一大堆静态函数来实现一个类。您可以这样做,但确实没有必要。与其他语言不同,python 不需要类来运行。你可以定义你的方法没有类

    def add(x, y):
        answer = x + y
        print(answer)
    
    add(5, 7)
    

    由于python中的导入方式,命名空间的基本单元是模块,而不是

    from module import some_class  # works.
    from module import submodule  # works.
    from module.some_class import method  # doesn't work
    

    因此,您最好按照预期使用模块,而不是将类用作模块:-)。

    【讨论】:

      猜你喜欢
      • 2017-05-10
      • 2017-12-09
      • 2015-12-01
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      相关资源
      最近更新 更多