Assigning Function to a Variable
The function in Python is an object, so it can be assigned to a variable. As a result, we can have an alias that refers to the same object as the function name does.
var = func_name
With the function name, we don’t use parentheses or parameters, only the name. Now, we can do anything with such a variable. Among others, we can pass such a variable.
def dzial1(a,b):
return a*b
def dzial2(a,b,c):
return a*b*c
Let’s assign our two functions to the two variables:
zm1 = dzial1
zm2 = dzial2
Now, we can check if our aliases refer to the same objects as the function names:
>>> zm1=dzial1
>>> zm2=dzial2
>>> type(zm1)
<class ‘function’>
>>> type(zm2)
<class ‘function’>
>>> print(zm1)
<function dzial1 at 0x00C76300>
>>> print(zm2)
<function dzial2 at 0x00C76420>
>>> print(zm1(2,3))
6
>>> print(zm2(2,3,4))
24
>>> print(dzial1(2,3))
6
>>> print(dzial2(2,3,4))
24
>>>
What about the built-in functions? Yes, we can assign them to variables too. For example, let’s take the built-in function max():
>>> max(1,2,3,4)
4
>>> wbud = max
>>> wbud(1,2,3,4)
4
>>>
Let’s check:
>>> type(max)
<class ‘builtin_function_or_method’>
>>> type(wbud)
<class ‘builtin_function_or_method’>
>>> print(max)
<built-in function max>
>>> print(wbud)
<built-in function max>
>>> print(max(5,1,9))
9
>>> print(wbud(5,1,9))
9
>>>
We can call the function using its alias, and this calling is an indirect call.
def dzial3(a,b,c,d):
return 1+2+3+4
Let’s try to make more aliases for our function:
f = dzial3
e = f
d = e
Now, we can check:
>>> f = dzial3
>>> e = f
>>> d = e
>>> e
<function dzial3 at 0x00C76468>
>>> type(e)
<class ‘function’>
>>>
We can also assign more functions to variables, and we will use a tuple:
>>> x,y,z = dzial1,dzial2,dzial3
>>> x
<function dzial1 at 0x00C76300>
>>> y
<function dzial2 at 0x00C76420>
>>> z
<function dzial3 at 0x00C76468>