Factory functions (a.k.a. closures) create and return functions.
def maker(N): def action(X): # Make and return action return X ** N # action retains N from enclosing scope return action f = maker(2) # Pass 2 to argument N print( f ) print( f(3) ) # Pass 3 to X, N remembers 2: 3 ** 2 print( f(4) ) # 4 ** 2 # from w w w .j a va 2 s.c om #We get the argument cubed when calling the new function, #but the original still squares as before: g = maker(3) # g remembers 3, f remembers 2 print( g(4) ) # 4 ** 3 print( f(4) ) # 4 ** 2
A lambda would serve in place of a def:
def maker(N): return lambda X: X ** N # lambda functions retain state too # w w w . java 2 s . c o m h = maker(3) print( h(4) ) # 4 ** 3 again