【问题标题】:How to pass a list of function names as a parameter?如何将函数名称列表作为参数传递?
【发布时间】:2017-07-22 16:46:00
【问题描述】:

如何在 Python 中使用函数名作为参数? 例如:

def do_something_with(func_name, arg):
    return func_name(arg)

其中 'func_name' 可能是 'mean'、'std'、'sort' 等。

例如:

import numpy as np
func_list = ['mean', 'std']

for func in func_list:
    x = np.random.random(10)
    print do_something_with(func, x)

当然,结果应该是在我的数组“x”上成功应用“mean”和“std”。

【问题讨论】:

标签: python function


【解决方案1】:

作为 cmets 中的建议,将列表中的函数对象传递给您的函数并调用它们。这不仅适用于numpy,还适用于所有 Python 函数:

import numpy as np
func_list = [np.mean, np.std]

for func in func_list:
    x = np.random.random(10)
    print func(x)

确保函数调用以相同的方式工作,即x 作为第一个参数。

以上内容与函数重命名的工作方式非常相似:

import time

another_sleep = time.sleep
another_sleep(1)  # Sleep for one second

您创建一个函数对象 (time.sleep) 并将其分配给一个变量 (another_sleep)。现在您可以使用变量名称 (another_sleep(1)) 调用它。

【讨论】:

    【解决方案2】:

    Tadhg McDonald-Jensen 的解决方案是正确的,因为函数在 Python 中是一等公民。另外,我还有一个想法:

    from operator import methodcaller
    
    import numpy as np
    
    
    func_list = ['mean', 'std']
    for func in func_list:
        x = np.random.random(10)
        f = methodcaller(func, x)
        result = f(np)
        print(result)
    

    在某些情况下,您可以使用operator.methodcaller

    【讨论】:

    • 这很有趣!谢谢!
    • f(np) 这里np 代表包含meanstd 方法的类名