以 Python 2.7 中的参数命名的关键字参数闭包
Closure with keyword arguments named after parameters in Python 2.7
我需要在运行时动态声明一个具有任意数量的命名参数(关键字)的函数,以便不同的库可以使用字典作为参数调用该函数。这是我需要的示例:
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 的参数实际上将作为字典传递。如果 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
实际上您甚至可以删除 *names
。
我需要在运行时动态声明一个具有任意数量的命名参数(关键字)的函数,以便不同的库可以使用字典作为参数调用该函数。这是我需要的示例:
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 的参数实际上将作为字典传递。如果 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
实际上您甚至可以删除 *names
。