如何将函数名称列表作为参数传递?

时间:2017-03-02 19:26:09

标签: python function

如何在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'。

2 个答案:

答案 0 :(得分:6)

作为评论中的建议,将列表中的函数对象传递给函数并调用它们。这不仅适用于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))来调用它。

答案 1 :(得分:4)

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

相关问题