Fidel Castro Fidel Castro - 20 days ago 5
Python Question

TypeError: unbound method mult() must be called with calculadora instance as first argument (got int instance instead)

I get a
TypeError: unbound method mult() must be called with calculadora instance as first argument (got int instance instead)

when running my python file :

from __future__ import print_function

class calculadora:


def suma(x,y):
added = x + y
print(added)

def resta(x,y):
sub = x - y
print(sub)

def mult(x,y):
multi = x * y
print(multi)


calculadora.mult(3,5)

Answer

If you want to access methods as static methods(accesing methods without the clas instance), you need to decorate them with @staticmethod:

class calculadora:
    @staticmethod
    def suma(x, y):
        added = x + y
        print(added)

    @staticmethod
    def resta(x, y):
        sub = x - y
        print(sub)

    @staticmethod
    def mult(x, y):
        multi = x * y
        print(multi)

If you meant instance methods, you need to create instance first. and need to modify methods' signatures to include self as the first parameter:

class calculadora:
    def suma(self, x, y): # not `self`, refering class instance
        added = x + y
        print(added)

    def resta(self, x, y):
        sub = x - y
        print(sub)

    def mult(self, x, y):
        multi = x * y
        print(multi)


c = calculadora()  # Create instance
c.mult(3,5)  # Access the method through instance, (not class)