Function as a variable in Python
In Python, a function is essentially a variable. This means that it can also be passed around.
Let's say we have a function that returns an exclamation mark:
def func():
return '!'
Let's pass the function name without parentheses as a variable to print
:
print(func)
After executing the code, a special object containing information about this function will be output to the console:
<function func at 0x0000022816383E20>
Now let's declare a variable func2
, to whose value we will pass the function func1
. The function itself will be passed not by value, but by reference as an object. And when calling func2
with parentheses, the result of func1
will be printed to the console:
def func1():
print('!')
func2 = func1
func2() # '!'
What will be the result of running the following code:
def func():
print('hello, user!')
greet = func
print(greet)
What will be the result of running the following code:
def getSum(num1, num2):
res = num1 + num2
return res
func = getSum
print(func(2, 3))