What is first class function in Python

前端 未结 8 1243
情话喂你
情话喂你 2020-12-08 10:28

I am still confused about what first-class functions are. If I understand correctly, first-class functions should use one function as an object. Is

8条回答
  •  北海茫月
    2020-12-08 10:59

    No. You are talking about higher-order functions -- refer.

    First class functions: If a function can be assigned to a variable or passed as object/variable to other function, that function is called as first class function.

    Python, JavaScript and C(pointers) support first class functions.

    A simple example (in python):

    def square(x): return x * x
    def cube(x): return x * x * x
    
    def print_result(x, func):
        """recieve a function and execute it and return result"""
        return func(x)
    
    do_square = square     # assigning square function to a variable
    do_cube = cube         # assigning cube function to a variable
    
    res = print_result(5, do_square)   # passing function to another function
    print res
    res = print_result(5, do_cube)
    print res
    

    This program is just for illustration.

提交回复
热议问题