Assigning a function to a variable

前端 未结 5 963
灰色年华
灰色年华 2020-11-28 06:24

Let\'s say I have a function

def x():
    print(20)

Now I want to assign the function to a variable called y, so that if I us

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 06:59

    The syntax

    def x():
        print(20)
    

    is basically the same as x = lambda: print(20) (there are some differences under the hood, but for most pratical purposes, the results the same).

    The syntax

    def y(t):
       return t**2
    

    is basically the same as y= lambda t: t**2. When you define a function, you're creating a variable that has the function as its value. In the first example, you're setting x to be the function lambda: print(20). So x now refers to that function. x() is not the function, it's the call of the function. In python, functions are simply a type of variable, and can generally be used like any other variable. For example:

    def power_function(power):
          return  lambda x : x**power
    power_function(3)(2)
    

    This returns 8. power_function is a function that returns a function as output. When it's called on 3, it returns a function that cubes the input, so when that function is called on the input 2, it returns 8. You could do cube = power_function(3), and now cube(2) would return 8.

提交回复
热议问题