简体   繁体   中英

Can anyone explain, how this peice of code works?

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

mydoubler = myfunc(2)

print(mydoubler(11))

The value of n = 2, after that I'm confused what is the value of a, and how the lambda function is executed.

Your myfunc is a nested function, lambda s are functions.

An equal implementation would be:

def outer(n):
    def inner(a):
        return a * n
    return inner

Which returns a function like your original myfunc as well. Since the return of the call of myfunc is also a function, you may well call the inner function as well.

When the outer function is called, the inner lambda creates a function. The outer lambda then returns the called function.

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