[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 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)
staticmethod for python2.7 in your case
class calc: 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 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)
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 print(answer) #call classmethod add_plus_one dircetly #without declaring instance but accessing class variables calc.add_plus_one(5,7)
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 :-).