I found a way to do what you are asking for:
class AddableInt(int):
def __call__(self, n):
return AddableInt(self + n)
def add(n):
return AddableInt(n)
add(5)(10)(20) # evaluates to 35
This works because the call to add(5)
creates an AddableInt
with a value of 5. No __init__
method was declared in AddableInt
, so it just uses int
‘s default constructor. The subsequent calls (10)(20)
each call AddableInt
‘s __call__
method, which adds the argument to itself and creates a new AddableInt
.
Old answer:
Python does not support what you are asking for. The closest I can come up with is:
from functools import partial
def add(n=None, terms=None):
if n is None:
return sum(terms) if terms else 0
else:
if terms:
terms.append(n)
else:
terms = [n]
return partial(add, terms=terms)
Call it like:
add(5)(10)(20)() # Note the extra parenthesis on the end
Better would be to use:
sum((5,10,20))
5
solved Python methods that add numbers given in parenthesis [closed]