繁体   English   中英

TypeError:必须使用实例作为第一个参数(在Python 2中使用int实例)调用unbound方法

[英]TypeError: unbound method must be called with instance as first argument (got int instance instead) in Python 2

在python 3中,下面的一组代码可以工作,我想知道为什么在python 2.7中它给我一个TypeError:unbound方法add()必须用calc实例作为第一个参数调用(改为使用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)

在你的情况下使用python2.7的staticmethod

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)

看起来你正试图用一大堆静态函数来实现一个类。 可以做到这一点,但确实没有必要。 与其他语言不同,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

所以,你总是会更好地使用模块,因为它们是预期的而不是使用类作为模块:-)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM