【发布时间】:2018-05-31 11:05:11
【问题描述】:
假设我有一个 HOF
def some_func(lst):
def func(args):
if args[0]=='compute':
return sum(lst)
elif args[0]=='add':
XXXXX #Return a new HOF with the 2 sub HOF input parameters added together.
return func
x1=some_func([1,2,3])
x2=some_func([2,3,4])
HOF 的输入 *args 之一是 ('add', another_hof),这需要 HOF 添加另一个 HOF 参数并返回一个带有添加参数的 HOF。
示例:
x3=x1('add',x2)
x4=some_func([3,5,7])
那么,
x3 should equal x4.
test_case:
x1=some_func([1,2,3])
x2=some_func([2,3,4])
x1('compute')=6
x2('compute')=9
x3=x1('add',x2)
x3('compute')=15
当我对 x1 函数的 ('add,x2) 执行 x HOF 时,我是否可以知道函数 func(*args) 中的 x2' 输入参数 [2,3,4]?
【问题讨论】:
-
... 您不能使用名称
lst在func中访问它吗?似乎与访问任何其他变量没有什么不同。 -
你在
func中尝试过print(lst)吗?我猜不是。这与任何其他嵌套函数或装饰器没有什么不同 -
原谅我糟糕的英语。试图问我在为 x1 执行“添加”时是否有可能知道 HOF x2 参数
-
您可以在
func中访问lst,只要您不尝试在其中分配名称lst,因为这会告诉Python 将该名称视为本地名称的func。如果lst是一个实际的list,那么mutate 它是安全的。详情请见stackoverflow.com/questions/30157655/…。 -
如果我们不理解您的实际问题,那么您需要在您的问题中添加更多代码,以更准确地说明您想要做什么。所有这些 HOF 谈话都有点令人困惑:很难跟踪哪个 HOF 是哪个。 ;)
标签: python function input arguments higher-order-functions