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'
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
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())
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'
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
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())