【问题标题】:Get the input of an Higher order function in python在python中获取高阶函数的输入
【发布时间】: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]?

【问题讨论】:

  • ... 您不能使用名称lstfunc 中访问它吗?似乎与访问任何其他变量没有什么不同。
  • 你在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


【解决方案1】:

在我看来,问题的核心是:给定一个对func 实例的引用,您需要获取它包含的lst 值。

一种方法是向返回lst 的条件块添加另一种模式。我们就叫它get_lst

def some_func(lst):
    def func(*args):
        if args[0]=='compute':
            return sum(lst)
        elif args[0]=='add':
            new_lst = [a+b for a,b in zip(lst, args[1]("get_lst"))]
            return some_func(new_lst)
        elif args[0] == "get_lst":
            return lst
    return func

x1=some_func([1,2,3])
x2=some_func([2,3,4])
print(x1('compute'))
print(x2('compute'))
x3=x1('add',x2)
print(x3('compute'))

结果:

6
9
15

您还可以将lst 分配给函数对象的属性:

def some_func(lst):
    def func(*args):
        if args[0]=='compute':
            return sum(lst)
        elif args[0]=='add':
            new_lst = [a+b for a,b in zip(lst, args[1].params)]
            return some_func(new_lst)
    func.params = lst
    return func

x1=some_func([1,2,3])
x2=some_func([2,3,4])
print(x1('compute'))
print(x2('compute'))
x3=x1('add',x2)
print(x3('compute'))

【讨论】:

  • 谢谢,Kevin,从没想过我可以添加一个条件块。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2018-07-27
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
  • 2019-11-14
  • 1970-01-01
  • 2022-01-07
  • 2022-01-07
相关资源
最近更新 更多