0
about the "func"
About the section of "Function as Objects" 2/2 in tutorial, following code def square(x): return x*x def test(func,x): print(func(x)) test(square, 42) why my PC knows the func is the square(x)? Or "func" means just a function? Is the func the word that is placed to inform pc some function comes here?
3 Answers
+ 4
because you call test(square, 42).
as square is a function which declared at the begining of the script, inside the definition of test function it is replaced by the name 'func'
basically what happened is that for this specific code you could say what happened inside the function test was: print(square(42))
+ 2
consider ->
def add(a,b):
return a+b
add(3,7)
here when you call add(3,7) function 'add' is called and a=3 and b=7
so in computes a+b which is 3+7 and returns 10
def test(func,x):
print(func(x))
test(square,42)
does the same
when you call test func=square and x=42
so func(x) is actually square(42)
func is NOT a keyword
it is just the name of a parameter like x
if you replaced this test function with
def test(a,b):
print(a(b))
you would get the same result
0
thank you for your answers. and i got "funcion as object" in python. i will follow next chaper. thank you.