简体   繁体   中英

A question regarding the Lambda function in Python

Why in the following code, the output is 22?

In my understanding, we have a function that needs two arguments, but it has been defined with only one, However, the first time we use it in mydoubler = myfunc(2) , it assigns the argument(2) to variable n , but the second time we use it in print(mydoubler(11) , it uses the argument(11) to set the value of the variable a ? Why is that? Does Lambda work like a recursive function?

   def myfunc(n):
        return lambda a : a * n

   mydoubler = myfunc(2)

   print(mydoubler(11))

Basically what happens is this:

mydoubler = myfunc(2) is actually the same as writing mydoubler = lambda a: a * 2

The reason for this is that myfunc(2) returns lambda a: a * 2

So now mydoubler = lambda a: a * 2

Then when mydoubler(11) is called, it simply returns 11 * 2

You're returning a lambda, which is a one-liner function, NOT a number. The code below does the EXACT SAME thing, but is maybe a bit clearer as to its purpose:

def multiplier_factory(constant_factor):
    # Define our new function
    def multiplier(factor):
        result = constant_factor * factor
        return result
    # Return the FUNCTION, not a number
    return multiplier

doubler = multiplier_factory(2)
tripler = multiplier_factory(3)

print (doubler(1))  # prints 2
print (tripler(1))  # prints 3

print (doubler('a'))  # prints 'aa'
print (tripler('a'))  # prints 'aaa'

lambda a: a * n is the same of:

def somefunction(a):
    return a * n

When you called myfunc(2) you dynamically created a function that is the same of:

def somefunction(a):
    return a * 2

myfunc returns a function. So mydoubler is a function and is described by lamda a: a * 2 . Then you call that function with the argument 22 and so naturally 11 * 2 = 22 is printed. Lambda functions are not per se recursive, they are just a shorter way of writing a simple function. In your case you can also write:

def myfunc(n):
    def multiplier(a):
        return a * n

    return multiplier

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM