给定一个更高阶函数,它将多个函数作为参数,该函数如何将关键字参数传递给函数参数?
例如
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?
答案 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)
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