Search code examples
pythonpython-3.xtypeerrorpositional-argument

Missing 1 required positional argument: 'y'


I have created a Python class:

class calculator:
    
    def addition(self,x,y):
        added = x + y
        print(added)
        
    def subtraction(self,x,y):
        sub = x - y
        print(sub)

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

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

Now when I am calling the function like this:

calculator.addition(2,3)

I am getting an error:

addition() missing 1 required positional argument: 'y'

What is the problem? What could be the solution so that I can call it like addition(2,3)?


Solution

  • Python' classes have three types of methods:

    1. Instance method

    The instance method must pass the instance object as the first parameter to the method, which is self, like:

    class calculator:
        
        def addition(self, x, y):
            added = x + y
            print(added)
    
    c = calculator()        
    c.addition(2, 3)
    
    1. Class method

    The class method use classmethod decorator and must pass the class object as the first parameter to the method, which is cls, like:

    class calculator:
        
        @classmethod
        def addition(cls, x, y):
            added = x + y
            print(added)
        
    calculator.addition(2, 3)
    
    1. Static method

    The static method doesn’t matter, just add an staticmethod decorator, like:

    class calculator:
        
        @staticmethod
        def addition(x, y):
            added = x + y
            print(added)
        
    calculator.addition(2, 3)
    

    So, the last two ways can be your answer if you just want to call with a class object like calculator.addition(2, 3).