2
class sum:
    def fx(self, op, a, b, c, d):
        if(op == 1):
            self.output = self.addition(a, b, c, d)
        else:
            self.output = self.subtraction(a, b, c, d)

    def addition(self, a, b, c, d):
        return a+b+c+d

    def subtraction(self, a, b, c, d):
        return a-b-c-d

x = sum.fx(1, 1, 2, 3, 4)

The above code gives an error

x = sum.fx(1, 1, 2, 3, 4) TypeError: sum.fx() missing 1 required positional argument: 'd'

I am clearly entering the value parameter 'd' but it says that i am not. It should give an output "10"

Sh0unak
  • 23
  • 3
  • `sum` is the name of the class. You didn't create an instance of it, so calling a member method like that won't work this way. One way to make this work is `sum().fx(1, 1, 2, 3, 4)` – UnholySheep Jan 15 '23 at 21:39
  • `sum` is a class. You're supposed to declare an _instance_ of the class, like this `mysum = sum()` and then call the method on the instance `mysum.fx(...)` – John Gordon Jan 15 '23 at 21:44

2 Answers2

2

It should be sum().fx(...). The first argument you passed is considered to be the instance of the class (self) but if we consider that then you are missing one of the arguments d that you need to pass?

You should instantiate in this case first to call the methods.

Note: By using the self we can access the attributes and methods of the class in python. In your case, even if you provide extra random arguments .fx(1,1,2,3,4) it would run into error later. Because you don't have the instance of the class.

user2736738
  • 30,591
  • 5
  • 42
  • 56
1

Alternatively, if you want the sum class to be like a Library of mathematical functions you could declare the methods as @classmethods:

class Sum:
    @classmethod
    def fx(cls, op, a, b, c, d):
        if op == 1:
            output = cls.addition(a, b, c, d)
        else:
            output = cls.subtraction(a, b, c, d)
        return output

    @classmethod
    def addition(cls, a, b, c, d):
        return a+b+c+d

    @classmethod
    def subtraction(cls, a, b, c, d):
        return a-b-c-d

x = Sum.fx(1, 1, 2, 3, 4)
print(x)

This way you do not need to create a class instance, just use the functions

Galo do Leste
  • 703
  • 5
  • 13