首页 > 编程语言 > 详细

Pythonの坑

时间:2017-04-11 15:05:19      阅读:240      评论:0      收藏:0      [点我收藏+]

Python closures and late binding

A closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution.

def make_printer(msg):
    def printer():
        print msg
    return printer

We can see that the printer() function depends on the variable msg which is defined outside the scope of it’s function.

Late binding and bad side-effects

Python’s closures are late binding. This means that the values of variables used in closures are looked up at the time the inner function is called.

def multipliers():
    return [lambda x : i*x for i in range(4)]

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

Then we expect the output of the print statement to be [0, 2, 4, 6] based on the element-wise operation [0*2, 1*2, 2*2, 3*2]. However, [3*2, 3*2, 3*2, 3*2] = [6, 6, 6, 6] is what is actually return. That is because i is not passed to the the lambda function until the loop for i in range(4) has been evaluated.

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]

 附:python十坑(英文), python十六坑(中文)

Pythonの坑

原文:http://www.cnblogs.com/dirge/p/6693296.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!