返回顶部

python3 之 闭包实例解析

一、实例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('3的100次方为:',pow100(3),"\t")

二、实例2(面试题):

#下面这段代码的输出结果是什么?请解释:
#代码:
def multipliers():
    return [lambda x: i * x for i in range(4)]
print([m(2) for m in multipliers()])
#输出结果:[6,6,6,6] #(不是我们想要的[0,2,4,6])
#原因:
#上述问题产生的原因是Python闭包的延迟绑定。这意味着内部函数被调用时,参数的值在闭包内进行查找。
#因此,当任何由multipliers()返回的函数被调用时,i的值将在附近的范围进行查找。那时,不管返回的函数是否被调用,for循环已经完成,i被赋予了最终的值3。

解决办法:

  方法1:python生成器  

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

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

  方法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]
posted @ 2019-08-07 17:06  Be-myself  阅读(1265)  评论(0编辑  收藏  举报
levels of contents 点击查看具体代码内容