What is the right way to implement addition using class in Python and avoid TypeError with missing positional argument?

Question:

class Add:

    def __init__(self,a,b):
        self.a = a
        self.b = b

    def add(a,b):
       return self.a + self.b

obj = Add(3,4)
print(obj.add())

Error message:

print(obj.add())
          ^^^^^^^^^
TypeError: Add.add() missing 1 required positional argument: 'b'
Asked By: Madhu

||

Answers:

You should only take self as a parameter. The other values are accessed on the instance itself.

def add(self):
   return self.a + self.b
Answered By: Unmitigated
class Add:

    def __init__(self,a,b):
        self.a = a
        self.b = b

    def add(self):
        return self.a + self.b

obj = Add(3,4)
print(obj.add())
Answered By: Tourelou
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.