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

守給你的承諾、 提交于 2020-12-12 04:01:39

问题


In python 3 the following set of codes works, I wonder why in python 2.7 it gives me a TypeError: unbound method add() must be called with calc instance as first argument(got int instance instead)? how do I resolve this in 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)

回答1:


Use staticmethod for python2.7 in your case

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)

Or, Use instance method if you need to call other instance methods or use anything inside class

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) 

Additionally, Use classmethod if you need to use class variables but without declaring instance

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:


It looks like you are trying to implement a class with a whole bunch of static functions. You can do that, but there really is no need. Unlike other languages, python does not require classes to function. You can define your methods without the class:

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

add(5, 7)

Because of the way importing works in python, the fundamental unit of namespace is the module, not the class.

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

So, you'll always be better off using modules as they were intended and not using classes as modules :-).



来源:https://stackoverflow.com/questions/40701142/typeerror-unbound-method-must-be-called-with-instance-as-first-argument-got-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!