Pass Function To Function With Different Number Of Variables
Suppose I have a function def foo(A, B). Now I have another function bar(func), where func is a function that takes only one variable. I want to pass in foo as func, but with the s
Solution 1:
You use lambda
:
bar(lambda x: foo(x,300))
basically,
func = lambda x: x*x
is more or less equivalent to:
def func(x):
return x*x
So in this case, we use something that's more or less equivalent to:
defnew_func(x):
return foo(x,300)
and then we pass the equivalent of new_func
to bar
.
Solution 2:
Lambda is easiest, but you could also use functools.partial for more complex cases:
import functools
bar(functools.partial(foo, B=300))
Post a Comment for "Pass Function To Function With Different Number Of Variables"