Priyanshu Kedia
Priyanshu Kedia

Reputation: 21

Python class and method instantiation

Here is my code:

class calculator:

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

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

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

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

calculator.addition(5,7)

This program gives me the following error:

Traceback (most recent call last):
  File "C:/Python27/docs/defin_class.py", line 21, in <module>
    calculator.addition(6,3)
TypeError: unbound method addition() must be called with calculator instance as first argument (got int instance instead)

I don't understand the mistake. Please help.

Upvotes: 1

Views: 41

Answers (1)

jamoque
jamoque

Reputation: 61

So without going too much into the nitty-gritty, you should add @staticmethod decorators above each function, like I've done below:

class calculator:

    @staticmethod
    def addition(x,y):
        added=x+y
        print(added)

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

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

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

calculator.addition(5,7)

The reason is that all of these methods are functions of the calculator, but they do not operate on an object of the calculator class.

For a great overview of the different types of methods you should use in Python, I highly recommend this blog post. Best of luck!

Upvotes: 1

Related Questions