def apply_twice(func,arg):
return func(func(arg))
def add_five(x):
return x+5
print (apply_twice(add_five,10))
The output I get is 20.
This one is actually confusing me like how is it working.Can anybody explain me how this is working by breaking it down
The function apply_twice(func,arg)
takes two arguments, a function object func
and an argument to pass to the function func
called arg
.
In Python, functions can easily be passed around to other functions as arguments, they are not treated differently than any other argument type (ie first class citizens ).
Inside apply_twice
, func
is called twice in the line:
func(func(arg))
Which, alternatively, can be viewed in a more friendly way as:
res = func(arg)
func(res)
If you replace func
with the name of the function passed in add_five
you get the following:
res = add_five(arg) # equals: 15
add_five(res) # result: 20
which, of course, returns your expected result.
The key point to remember from this is that you shouldn't think of functions in Python
as some special construct, functions are objects just like int
s, lists
s and everything else is.
Expanding the code it executes as follows, starting with the print
call:
apply_twice(add_five,10))
add_five(add_five(10)) # add_five(10) = 15
add_five(15) # add_five(15) = 20
Which gives you the result: 20.
When apply_twice
is called, you are passing in a function object and a value. As you can see in the apply_twice
definition, where you see func
that is substituted with the function object passed to it (in this case, add_five
). Then, starting with the inner func(arg)
call, evaluate the result, which is then passed to add_five
again, in the outer return func( ... )
call.
What you need to understand here is that
apply_twice(func,arg)
is a higher function which accepts two arguments (another function named func
and an argument arg
). The way it works is that it first evaluate the value of the other function, then use the value as an argument inside the higher function.
remember we have a function add_five(x)
which add 5 to the argument supply in it... then this function add_five(x)
is then passed as an argument to another function called apply_twice_(func,arg)
which return func(func(arg))
.
now splitting func(func(arg))
we have func(arg)
#lets called it a
then func(func(arg))==func(a
) since a = func(agr)
and (a)
is our add_five(x)
function, after it add 5, then the value we got is re-used as another fresh argument to add another 5 to it, that is why we have 20 as our result.
Another example is:
def test(func, arg):
return func(func(arg))
def mult(x):
return x * x
print(test(mult, 2))
which give 16 as result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.