In different programming languages, First Class objects are those objects, which can be handled uniformly. First Class objects can be stored as Data Structures, as some parameters of some other functions, as control structures etc. We can say that a function in Python is First Class Function, if it supports all of the properties of a First Class object.
At first we will see how Functions in Python can be used as an object. In Python, a function can be assigned as variable. To assign it as variable, the function will not be called. So parentheses '()' will not be there.
def cube(x): return x*x*x res = cube(5) print(res) my_cube = cube #The my_cube is same as the cube method res = my_cube(5) print(res)
Now we will see how functions can be passed as argument of another functions. Here is the example.
def cube(x): return x*x*x defmy_map(method, argument_list): result = list() for item in argument_list: result.append(method(item)) return result my_list = my_map(cube, [1, 2, 3, 4, 5, 6, 7, 8]) #Pass the function as argument print(my_list)
[1, 8, 27, 64, 125, 216, 343, 512]
Here is the third property of First Class Functions. In this case we will return one function from another function.
defcreate_logger(message): deflog(): print('Log Message: ' + message) return log #Return a function my_logger = create_logger('Hello World') my_logger()
Log Message: Hello World