【发布时间】:2016-12-26 18:41:25
【问题描述】:
我需要在运行时动态声明一个具有任意数量的命名参数(关键字)的函数,以便不同的库可以使用字典作为参数调用此函数。这是我需要的示例:
def generateFunction(*kwrds):
#kwrds are a bunch of strings
def functionTheLibraryCalls('''an argument for every string in kwrds '''):
#Get all arguments in a tuple in the order as listed above
result = tuple(args)
#Code that needs to be executed inside the library,
#it can handle a variable number of arguments
return result
return functionTheLibraryCalls
f1 = generateFunction('x', 'y','z')
print f1(x = 3,y = 2, z = 1)
#>> (3,2,1)
f2 = generateFunction('a', 'b')
print f2(a = 10, b = 0)
#>> (10,0)
这在 python 2.7 中可能吗? f1 和 f2 的参数实际上将作为 dict 传递。如果 lambda 对此更好,那也没关系。
谢谢!
【问题讨论】:
标签: python-2.7 dynamic lambda closures named-parameters