Python 2.7 在Python2.7中使用以参数命名的关键字参数进行闭包
我需要在运行时动态声明具有任意数量命名参数(关键字)的funktion,以便其他库可以使用字典作为参数调用此函数。以下是我需要的一个示例:Python 2.7 在Python2.7中使用以参数命名的关键字参数进行闭包,python-2.7,dynamic,lambda,closures,named-parameters,Python 2.7,Dynamic,Lambda,Closures,Named Parameters,我需要在运行时动态声明具有任意数量命名参数(关键字)的funktion,以便其他库可以使用字典作为参数调用此函数。以下是我需要的一个示例: 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
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)
这在Python2.7中可能吗?f1和f2的参数实际上将作为dict传递。如果lambda更适合于此,也可以
谢谢大家! 这就是你想要的
def generateFunction(*names):
#kwrds are a bunch of strings
def functionTheLibraryCalls(**kwrds):
#Code that needs to be executed inside the library,
#it can handle a variable number of arguments
print names, kwrds
return 42
return functionTheLibraryCalls
实际上,你甚至可以删除*名称。这就是你想要的吗
def generateFunction(*names):
#kwrds are a bunch of strings
def functionTheLibraryCalls(**kwrds):
#Code that needs to be executed inside the library,
#it can handle a variable number of arguments
print names, kwrds
return 42
return functionTheLibraryCalls
实际上,您甚至可以删除*名称