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

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

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

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

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

calc.add(5, 7)

Solution #1:

Use staticmethod for python2.7 in your case

class calc:

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

#call staticmethod add directly 
#without declaring instance and accessing class variables

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

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

class calc:

    some_val = 1

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

#call classmethod add_plus_one dircetly
#without declaring instance but accessing class variables
Respondent: Kir Chou

Solution #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

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 :-).

Respondent: mgilson

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.