注意,函数应该是函数,而不是字符串,这样实现才能工作
如果您想返回使用一组kwargs 调用的函数,那么您已经非常接近了。我会为func 使用位置参数,然后您可以将kwargs 传递给func,这更明确一点:
def myfunc(func, **kwargs):
return func(**kwargs)
然后,您可以将每对 func, **kwargs 包装为元组,然后执行 for 循环:
# This would be called like
somelist = [(np.random.normal, { 'loc' : 0 , 'scale' : 1 , 'size' : 7 }),
(np.random.uniform , { 'low' : 0 , 'high' : 1 , 'size' : 7 })]
results = []
# append results to a list
for func, kwargs in somelist:
results.append(myfunc(func, **kwargs))
通过这种方式,您不必担心您的任何变量命名,而且它更具可读性。您知道循环将处理成对的项目,在本例中为 func, kwarg 对,您的函数可以显式处理这些项目
处理字符串调用
因此,有一些方法可以完成这项任务,虽然有点棘手,但总体上应该不会太糟糕。您需要修改 myfunc 来处理函数名称:
# func is now a string, unlike above
def myfunc(func, **kwargs):
# function will look like module.class.function
# so split on '.' to get each component. The first will
# be the parent module in global scope, and everything else
# is collected into a list
mod, *f = func.split('.') # f is a list of sub-modules like ['random', 'uniform']
# func for now will just be the module np
func = globals().get(mod)
for cls in f:
# get each subsequent level down, which will overwrite func to
# first be np.random, then np.random.uniform
func = getattr(func, cls)
return func(**kwargs)
我使用globals().get(mod) 的原因是a) 我假设您可能并不总是使用相同的模块,并且b) 从sys.modules 调用重命名的导入将产生KeyError,这是'你想要什么:
import sys
import numpy as np
sys.modules['np'] # KeyError
sys.modules['numpy']
# <module 'numpy.random' from '/Users/mm92400/anaconda3/envs/new36/lib/python3.6/site-packages/numpy/random/__init__.py'>
# globals avoids the naming conflict
globals()['np']
# <module 'numpy.random' from '/Users/mm92400/anaconda3/envs/new36/lib/python3.6/site-packages/numpy/random/__init__.py'>
然后getattr(obj, attr) 将返回每个后续模块:
import numpy as np
getattr(np, 'random')
# <module 'numpy.random' from '/Users/mm92400/anaconda3/envs/new36/lib/python3.6/site-packages/numpy/random/__init__.py'>
# the dotted access won't work directly
getattr(np, 'random.uniform')
# AttributeError
所以,总共:
import numpy as np
func, kwargs = ('np.random.normal', { 'loc' : 0 , 'scale' : 1 , 'size' : 7 })
myfunc(func, **kwargs)
array([ 0.83276777, 2.4836389 , -1.07492873, -1.20056678, -0.36409906,
-0.76543554, 0.90191746])
您可以将其扩展到第一部分中的代码