Python Lessons – 3.6 Functions as objects

Python Lessons - 3.6 Functions as objects

Functions as variables

In Python anything can be considered as a variable, even functions. In fact, even though it may be a little intuitive at the beginning it is possible to assign a function to a variable, in this way it is as if we had given a new name to the variable.

def foo():
    print("Hello World")

variabile = foo
variabile()

If you run it, you get:

>>>
Hello World

The assignment of a variable of a function is well recognizable with respect to the assignment of a return value of a function to a variable, since the name of the function appears without round brackets.

variabile = foo   # funzione come valore della variabile

variabile = foo() # return value of the function as the value of the variable

Functions as arguments of other functions

Be careful not to get confused here too with the case of the value returned. Here is the whole function that is passed as an argument to a function. Also recognizable here due to the fact that the function does not present the round brackets.

def mix(a,b):
    return (a * b)/2

def foo(func,x,y):
    return func(x,y)

print(foo(mix,2,3)) 

If you run it, you get:

>>>
3.0

⇐ Go to Python Lesson 3.5 – Comments and Docstrings

Go to Python Lesson 3.7 – Modules ⇒

Leave a Reply