I am now trying to pass a multi-variable function F(x, y, z)
as an argument of another function G(F, x)
in Python. As written, the two arguments in function G is the function F and one of F's variables x. In other words, what I am trying to do is instead of passing F as a three-variable function, I'd rather pass it as a single variable function which depends only on x. The values of y and z are already assigned before calling G.
In Matlab, this is done simply by:
G((@x) F(x, y, z));
I am wondering if there is something similar in Python? I have tried to search online but I am not very familiar with the English wording for this particular question so no luck.
Higher Order Functions Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.
Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.
Functions, like any other object, can be passed as an argument to another function.
By default, arguments may be passed to a Python function either by position or explicitly by keyword.
lambda is suitable for this situation.
def G(func, x):
return func(x)
def F(x, y, z):
return x+y+z
print G(lambda x: F(x, 1, 2), 3)
It may be also done with functools.partial
In [158]:from functools import partial
In [159]: adder_w = partial(adder, y=5, z=10)
In [160]: adder_w(2)
Out[160]: 17
EDIT:
Sorry, I've forgotten to include function adder copied (I am lazy :) )from the @thefourtheye's answer
def adder(x, y, z):
return x + y + z
You can do it with Python closures and function currying technique, like this
def adder(x, y, z):
return x + y + z
def wrapper_g(y, z):
def g(f, x, y = y, z = z):
return f(x, y, z) # By closure property, `f` accesses `y` and `z`
return g
g = wrapper_g(5, 10) # We are creating `g` with default parameters 5 and 10
print g(adder, 20) # along with the third parameter 20, adder is called.
print g(adder, 40) # along with the third parameter 40, adder is called.
print g(multiplier, 2) # We can pass any function, which can act on 2 params.
print g(multiplier, 2, y = 3, z = 4) # We can dynamically alter the default param
Output
35
55
100
24
Advantages:
We can dynamically decide which function to be invoked
We even get to alter the default parameters, while calling.
It can be as simple as this
def F(x,y,z):
print "x=",x
print "y=",y
print "z=",z
def G(func,x):
func(x,"G's Y", "G's Z")
G(F,"Main's X")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With