Separating **kwargs for different functions
给定一个更高阶函数,它将多个函数作为参数,该函数如何将关键字参数传递给函数参数?
例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 This parrot is dead. skit(eat, parrot_is, food='spam', how_much=50, state='an ex-parrot') # error |
您可以根据函数的
1 2 3 4 | 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}) |
另请参阅:您是否可以列出Python函数接收的关键字参数?
如果将
1 2 3 4 5 6 7 8 9 10 11 | 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) |
例:
1 2 3 | >>> skit(eat, parrot_is, food='spam', how_much=50, state='an ex-parrot') spamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspamspam This parrot is an ex-parrot. |