Just started learning python and came across this
def f(g):
return g(2)
def square(x):
return x ** 2
print(f(square)) # which gives 4
How does inputting square into the f
function equate to 4
?
Just started learning python and came across this
def f(g):
return g(2)
def square(x):
return x ** 2
print(f(square)) # which gives 4
How does inputting square into the f
function equate to 4
?
When you call a function, the value of the argument is assigned to the named parameter. The call
print(f(square))
can be thought of as "expanding" to
g = square
print(g(2))
In python functions are first-class values, considered objects as anything else, hence you can pass them as parameters to another function.
In your case, you are "composing" f
with g
, which in turn has an invocation with fixed 2
inside f. In this sense, f is a function whose purpose is to feed 2 into another function, given as argument.
Knowing that g
squares a number, it's easy to see how g(2)
is 4, then f(g) will return 4.