如何在python中实现像sum(2)(3)(4)......(n)之类的函数? [英] how to implement a function like sum(2)(3)(4)......(n) in python?
问题描述
如何实现将在python中以以下方式sum_numbers(2)(3)(4)......(n)
调用的函数?
how to implement a function that will be invoked in the following way sum_numbers(2)(3)(4)......(n)
in python?
结果应为2+3+4+.....+n
我的提示是,由于函数是python中的对象,因此可以使用嵌套函数来实现这些功能,但我不确定.
The hint that I have is since functions are object in pythons there is way to do those using a nested function but I am not sure.
def sum_number(x):
def sum_number_2(y):
def sum_number_3(z):
....................
def sum_number_n(n)
return n
return sum_number_n
return sum_number_3
return sum_number_2
return sum_number
但是,不用编写太多的嵌套函数,我们应该能够以以下两个调用sum_numbers(2)(3)(4)......(n)
But instead of writing so many nested functions we should be able to do it in couple nested functions to compute sum of n values when invoked in the following way sum_numbers(2)(3)(4)......(n)
推荐答案
使用Python的数据模型功能将结果转换为所需的类型.
Use Python's data model features to convert the result into the desired type.
class sum_number(object):
def __init__(self, val):
self.val = val
def __call__(self, val):
self.val += val
return self
def __float__(self):
return float(self.val)
def __int__(self):
return int(self.val)
print '{}'.format(int(sum_number(2)(3)(8)))
print '{}'.format(float(sum_number(2)(3)(8)))
这篇关于如何在python中实现像sum(2)(3)(4)......(n)之类的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!