Home > Enterprise >  Can anyone explain, how this peice of code works?
Can anyone explain, how this peice of code works?

Time:12-01

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.

CodePudding user response:

Your myfunc is a nested function, lambdas 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.

CodePudding user response:

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

  • Related