Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4586831
  • 博文数量: 1214
  • 博客积分: 13195
  • 博客等级: 上将
  • 技术积分: 9105
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
个人简介

C++,python,热爱算法和机器学习

文章分类

全部博文(1214)

文章存档

2021年(13)

2020年(49)

2019年(14)

2018年(27)

2017年(69)

2016年(100)

2015年(106)

2014年(240)

2013年(5)

2012年(193)

2011年(155)

2010年(93)

2009年(62)

2008年(51)

2007年(37)

分类: Python/Ruby

2012-04-29 13:16:09

source:http://ynniv.com/blog/2007/08/closures-in-python.html
A closure is data attached to code (pretty simple, eh?). I use them for:
  • Replacing hard coded constants
  • Eleminating globals
  • Providing consistent function signatures
  • Implementing Object Orientation
(Isn't it funny that people rarely tell you what closures are good for?)

Ceder's uses a closure as part of the @decorator pattern (section 9.8).

Here is a closure in python:
def makeInc(x):
def inc(y):
# x is "closed" in the definition of inc
return y + x

return inc

inc5 = makeInc(5)
inc10 = makeInc(10)

inc5 (5) # returns 10
inc10(5) # returns 15Closures in python are created by function calls. Here, the call to makeInc creates a binding for x that is referenced inside the function inc. Each call to makeInc creates a new instance of this function, but each instance has a link to a different binding of x. The example shows the closure of x being used to eliminate either a global or a constant, depending on the nature of x.
import time
keepRunning = True
updates = []
def runLoop():
while (keepRunning):
for u in updates:
u()

class foo:
def __init__(self, x = 0):
self.x = x

def update(self):
print self.x
self.x += 1

f = foo()
g = foo(2)

updates.extend([f.update, g.update])In python, all methods (but not functions) are closures ... sort of. The method definition foo.update closes the class foo. The value of g.update is a closure that stores the value of g and passes that as the first argument of foo.self, hence the first argument of a method in python is self. Details aside, it is important to note that the designers of python have gone out of their way so that you can pass g.update by itself to another function and have it continue to work correctly.

Caveats

In some languages, the variable bindings contained in a closure behave just like any other variables. Alas, in python they are read-only. This is similar to Java, and has the same solution: closing container objects. Closure of a dictionary or array won't let you assign a new dictionary or array, but will let you change the contents of the container. This is a common use pattern - every time you set a variable on self, you are changing the contents of a closed dictionary.
阅读(1606) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~