Python pass in variable assignments through a function wrapper
So I know that you can wrap a function around another function by doing the following.
def foo(a=4,b=3):
return a+b
def bar(func,args):
return func(*args)
so if I then called
bar(foo,[2,3])
the return value would be 5.
I am wondering is there a way to use bar to call foo with foo(b=12) where bar would return 16?
开发者_如何学运维Does this make sense? Thank you so much for your time ahead of time! And sorry for asking so many questions.
This requires the **kwargs
(keyword arguments) syntax.
def foo(a=4, b=3):
return a+b
def bar(func, *args, **kwargs):
return func(*args, **kwargs)
print bar(foo, b=12) # prints 16
Where *args
is any number of positional arguments, **kwargs
is all the named arguments that were passed in.
And of course, they are only *args
and **kwargs
by convention; you could name them *panda
and **grilled_cheese
for all Python cares.
Yep, you can also pass a dict in addition to (or instead of) the list:
def bar(func, args=[], kwargs={}):
return func(*args, **kwargs)
bar(foo, {'b':12})
精彩评论