edisonlz 发表于 2013-1-26 15:49:43

python 中的闭包

http://www.agoit.com/images/smiles/icon_sad.gif 什么是闭包?
闭包并不是什么新奇的概念,它早在高级语言开始发展的年代就产生了。闭包(Closure)是词法闭包(Lexical Closure)的简称。对闭包的具体定义有很多种说法,这些说法大体可以分为两类:
一种说法认为闭包是符合一定条件的函数,比如参考资源中这样定义闭包:闭包是在其词法上下文中引用了自由变量(注 1)的函数。
另一种说法认为闭包是由函数和与其相关的引用环境组合而成的实体。比如参考资源中就有这样的的定义:在实现深约束(注 2)时,需要创建一个能显式表示引用环境的东西,并将它与相关的子程序捆绑在一起,这样捆绑起来的整体被称为闭包。


#python 中的闭包... def func(data):...   count = ...   def wrap():...         count += 1...         return count...   return wrap... ... a = func(1)>>> a()5: 2>>> a()6: 3 def func(x):...   return lambda y :y+x>>> b = func(1)>>> b(1)7: 2>>> b(2)8: 3>>> print b #这里b是个function 在ruby中是proc<function <lambda> at 0x01AC68F0> def addx(x):...def adder (y): return x + y...return adder>>> add8 = addx(8)>>> add8(8)9: 16



#ruby 中的闭包#   Creates a new <code>Proc</code> object, bound to the current#   context. <code>Proc::new</code> may be called without a block only#   within a method with an attached block, in which case that block is#   converted to the <code>Proc</code> object.#sum = 010.times{|n| sum += n}print sumdef upto(from,to)    while from <= to       yield from      from+=1    endendupto(1,10) {|n| puts n}def counter()i = 1Proc.new{ puts i;i+=1}endc = counter()c.call() 1c.call() 2
/*javascript中的闭包*/function f1(){    n=999;    function f2(){      alert(n);     }    return f2;  }  var result=f1();  result(); // 999//用途 setInterval 传参数function do_load_stock(market,code){return function(){load_stock(market,code)};}function time_loader(market,code){var stock = market+code;if(CheckStockTime(stock)){setInterval(do_load_stock(market,code),30000);}}
页: [1]
查看完整版本: python 中的闭包