【问题标题】:Closure with keyword arguments named after parameters in Python 2.7用 Python 2.7 中的参数命名的关键字参数闭包
【发布时间】: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


    【解决方案1】:

    这就是你想要的?

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-29
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 2013-08-16
      • 2020-02-07
      • 2011-03-09
      • 1970-01-01
      相关资源
      最近更新 更多