In python, functions are first class objects in python.
Advantages of first class objects:
- We can treat functions like other normal objects like int, string, list etc
- We can pass functions as another function arguments, return a function in another function and assign a function to another variable
- Define a function within a function (Inner functions)
- This first class object plays a key role in python for decorator design pattern.
Examples:
# Simple function for adding two numbers def add_num(num1, num2): return num1 + num2 # Passing function as a first argument def add_values(fun, arg1, arg2): result = fun(arg1, arg2) return result
- Assigning function name to the variable:
fun = add_num
- Passing function as a parameter
two_num_sum = add_values(fun, 5, 8))
Top comments (0)