为不同的功能分离** kwargs

时间:2014-05-02 14:13:50

标签: python function kwargs keyword-argument

给定一个更高阶函数,它将多个函数作为参数,该函数如何将关键字参数传递给函数参数?

例如

def eat(food='eggs', how_much=1):
    print(food * how_much)


def parrot_is(state='dead'):
    print("This parrot is %s." % state)


def skit(*lines, **kwargs):
    for line in lines:
        line(**kwargs)

skit(eat, parrot_is)  # eggs \n This parrot is dead.
skit(eat, parrot_is, food='spam', how_much=50, state='an ex-parrot') # error

state不是eat的关键字arg,那么skit如何才能传递与其调用的函数相关的关键字args?

3 个答案:

答案 0 :(得分:9)

您可以根据函数的kwargs过滤func_code.co_varnames字典:

def skit(*lines, **kwargs):
    for line in lines:
        line(**{key: value for key, value in kwargs.iteritems() 
                if key in line.func_code.co_varnames})

另见:Can you list the keyword arguments a Python function receives?

答案 1 :(得分:6)

如果您将**kwargs添加到所有定义中,则可以传递整个批次:

def eat(food='eggs', how_much=1, **kwargs):
    print(food * how_much)


def parrot_is(state='dead', **kwargs):
    print("This parrot is %s." % state)


def skit(*lines, **kwargs):
    for line in lines:
        line(**kwargs)

**kwargs中任何不是明确的关键字参数的内容都会留在kwargs中,并被例如{ eat

示例:

>>> skit(eat, parrot_is, food='spam', how_much=50, state='an ex-parrot')
spamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspam
This parrot is an ex-parrot.

答案 2 :(得分:-1)

def sample(a,b,*,c=0): print(a,b,c)

*->在参数为args之前和参数为kwargs(关键字参数)之后

sample(1,2,c=10) sample(a=1,b=2,c=1) # this also work sample(1,2,c) # TypeError: sample() takes 2 positional arguments but 3 were given