Reputation: 61
You need to write a function on python that is called an indefinite number of times, each time it takes a number and returns their sum, for example sum (1) (2) (3) == 6. I found the code for javascript, but I did not find how to redefine it in python __str __ method for the function. How can I override a method or is there another solution?
The code I tried to write:
def sum(n):
total = n
def f(k):
nonlocal total
total += k
# f.__str__ = lambda : print(total) # no
return f
return f
print(sum(1)(2)(3))
This is working javascript code:
function sum(a) {
let currentSum = a;
function f(b) {
currentSum += b;
return f;
}
f.toString = function() {
return currentSum;
};
return f;
}
alert( sum(1)(2) ); // 3
alert( sum(5)(-1)(2) ); // 6
alert( sum(6)(-1)(-2)(-3) ); // 0
alert( sum(0)(1)(2)(3)(4)(5) ); // 15
Upvotes: 0
Views: 2430
Reputation: 806
What about this:
def summ(a):
current_sum = a
return lambda x: current_sum + x
print(summ(1)(2))
>>>3
Upvotes: 0
Reputation: 12015
It is better to use a class
instead of an inner function, and return an object of that class. You would then be able to use the magic __call__
method again and again, if you make it return the same object.
def sum(n):
class Sum(object):
def __init__(self, k):
self.total = k
def __call__(self, k):
self.total += k
return self
def __str__(self):
return str(self.total)
def __repr__(self):
return str(self)
return Sum(n)
Output
>>> sum(1)
1
>>> sum(1)(2)
3
>>> sum(1)(2)(3)
6
Upvotes: 1
Reputation: 429
If the function is going to be used as func(a)(b)(c)(d)(...)
why not just use func([a,b,c,d,...])
? In this case:
sum([a,b,c,d])
Upvotes: 0