I would like to implement class 'Add' such that return the sum of the arguments passed in a separate set of parentheses using call method and inheritance in python. for example:
>>>Add(10)
10
>>>Add(10)(11)
21
>>>Add(10)(11)(12)
33
I tried this piece of code do not receive the expected result.
class Add():
def __init__(self, a):
self.a = a
def __call__(self, number):
print(self.a + number)
>>>Add(10)
10
>>>Add(10)(11)
21
but for the third time( Add(10)(11)(12) ) I received the error 'int object is not callable.'
UPDATE:
As per @jsbueno's suggestion of inheriting
intwill get you what is needed.This would let you use
Addobjects just like any otherintobjects.I am surprised with the error message you got :
int object is not callable.One would expect you would get'NoneType' object is not callable. At least that's what I got when I ran your code.To achieve what you want to achieve, you need to return the instance back to the call-site, so that you can
__call__it again.I would suggesting modifying your code like so:
You can then use it like:
Now this would change your original instance of
Add(10). If that is not something you would want, you would replace your__call__method with:This way, the base
Addinstance never really changes.