Search code examples
pythontypeerrorpositional-argument

Function missing 1 required positional argument


I'm getting this error :

Traceback (most recent call last):
  File "C:/Users/mali03/Desktop/Python/Practice/p2.py", line 18, in <module>
    first.subtraction(1, 2)
TypeError: subtraction() missing 1 required positional argument: 'y'

Here is my calculator class

class calculator:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def addition(self, x, y):
        return self.x + self.y

    def subtraction(self, x, y):
        if self.x > self.y:
            return self.y - self.x
        else:
            return self.x - self.y

I then call subtraction with the following:

first = calculator
first.subtraction(1, 2)

Solution

  • Like stated previously, you don't have to include parameters in your addition or subtraction functions if you already gather that information in the __init__ function.

    Like so:

    class calculator:
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def addition(self):
        return self.x + self.y
    
    def subtraction(self):
        if self.x > self.y:
            return self.y - self.x
        else:
            return self.x - self.y
    
    
    first = calculator
    print(first(5,10).addition())
    

    Alternatively, if you do want to have x and y parameters in your addition and subtraction functions, you can adjust your code like so:

    class calculator:
    
    def addition(self, x, y):
        return x + y
    
    def subtraction(self, x, y):
        if x > y:
            return y - x
        else:
            return x - y
    
    first = calculator
    print(first().addition(5, 10))
    

    Where parameters of individual functions are used instead to the parameters given to the class object.

    Either ways work, it depends on how you want to use the class.