Examples of analytical closure python3

I. Example 1:

 1 def make_power(y):
 2     def fn(x):
 3         return x**y
 4     return fn
 5 
 6 pow3 = make_power(3)
 7 pow2 = make_power(2)
 8 pow100 = make_power(100)
 9 
10 print('3的3次方=',pow3(3),"\t")
11 print('3的2次方为:',pow2(3),"\t")
12 print(' 100 3 power as: ' , pow100 (3), " \ T " )

Second, Example 2 (interview questions):

# What is the output of the following code is? Explain: 
# Code: 
DEF Multipliers ():
     return [ the lambda X: X I * for I in Range (. 4 )]
 Print ([m (2) for m in Multipliers ()]) 
# output: [6,6 , 6,6] # (not what we want [0,2,4,6])
# Reasons: 
Reason # problems described above is to delay the closure of the binding Python. This means that an internal function is called, the value of the parameter to find in the closure.
# Therefore, when any function of Multipliers () is called to return the value of i will be in the range around look. At that time, the function returns regardless of whether the calls, for the cycle has been completed, i was given a final value of 3.

Solution:

  Method 1: python generator  

def multipliers():
    for i in range(4):yield lambda x:x*i

print([m(2) for m in multipliers()])  #[0,2,4,6]

  Method 2:

def multipliers():
    return [lambda x,i = i :i*x for i in range(4)]
print([m(2) for m in multipliers()])  #[0,2,4,6]

Guess you like

Origin www.cnblogs.com/gengyufei/p/11316442.html