【发布时间】:2016-11-14 14:38:54
【问题描述】:
函数应该像 add(5)(10)(20) 并且答案应该是 35
即一个应该能够提供任意数量的括号。在python中
喜欢它应该适用于任意数量的括号。
【问题讨论】:
标签: python python-2.7
函数应该像 add(5)(10)(20) 并且答案应该是 35
即一个应该能够提供任意数量的括号。在python中
喜欢它应该适用于任意数量的括号。
【问题讨论】:
标签: python python-2.7
我找到了一种方法来满足您的要求:
class AddableInt(int):
def __call__(self, n):
return AddableInt(self + n)
def add(n):
return AddableInt(n)
add(5)(10)(20) # evaluates to 35
这是可行的,因为对add(5) 的调用创建了一个值为5 的AddableInt。在AddableInt 中没有声明__init__ 方法,所以它只使用int 的默认构造函数。随后的调用(10)(20) 每次调用AddableInt 的__call__ 方法,该方法将参数添加到自身并创建一个新的AddableInt。
旧答案:
Python 不支持您的要求。我能想到的最接近的是:
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)
这样称呼:
add(5)(10)(20)() # Note the extra parenthesis on the end
最好使用:
sum((5,10,20))
【讨论】:
在 python 中,您可以定义一个带有任意参数的函数,如下所示:
def add(*args):
total=0
for num in args:
total+=num
#or whatever you want to do with the numbers
return total
* 告诉代码从这里到结尾的所有参数都是可选的,并且可能不止一个。它将所有额外的参数存储在一个元组中。因此,如果您调用 add(5, 10, 20),它将返回 35,并且会像这样存储数字:
args=(5, 10, 20)
这是一个元组。它将多个值值存储在一个值中。所以参数 args 将等于整个元组。
This link 可能会对您有所帮助。
【讨论】: