0

Code :

class calculator:

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

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

    def multiplication(x,y):
        mul = x * y
        print (mul)

    def division(x,y):
        div = x / y
        print (div)

calculator.division(100,4)
calculator.multiplication(22,4)
calculator.subtraction(20,2)
calculator.addition(10,3)

when I run this code is gives Error :

Traceback (most recent call last): File "calculator.py", line 19, in calculator.division(100,4) TypeError: unbound method division() must be called with calculator instance as first argument (got int instance instead)

I am learning Python so can anyone solve this error.

4
  • 1
    you forgot to put self as the first argument in each function definition.. pythontips.com/2013/08/07/the-self-variable-in-python-explained Commented Feb 14, 2018 at 13:42
  • 1
    also, you need to invoke an instance of the class before calling the methods. Commented Feb 14, 2018 at 13:44
  • @Farhan.K can you modified my code Commented Feb 14, 2018 at 13:48
  • thanks @James actually i don't know more about python Commented Feb 14, 2018 at 13:51

2 Answers 2

1

There are a couple of things wrong with your code. First, you create a class, but you never instantiate an instance of that class. Such as:

class Calculator:
    ...
    ...

calculator = Calculator()

Second, methods called from an object always accept the object itself as the first argument. That is why you see self in the definition of methods. Even if you don't use self, it is still implicitly passed as the first argument.

class Calculator:

    def addition(self, x, y):
        add = x + y
        print(add)

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

    def multiplication(self, x, y):
        mul = x * y
        print(mul)

    def division(self, x, y):
        div = x / y
        print(div)


calculator = Calculator()
Sign up to request clarification or add additional context in comments.

1 Comment

no problem. please mark the question as answered (the check mark)
1

You can either make your functions static with @staticmethod (so you can call them without creating an instance)

class Calculator:
    @staticmethod
    def addition(x, y):
        add = x + y
        print(add)

Calculator.addition(10, 3)

or you add self as an argument and create an instance of Calculator.

class Calculator:
    def addition(self, x, y):
        add = x + y
        print(add)

calc = Calculator()
calc.addition(10, 3)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.