python 中的閉包

:( 什麼是閉包?
閉包並非什麼新奇的概念,它早在高級語言開始發展的年代就產生了。閉包(Closure)是詞法閉包(Lexical Closure)的簡稱。對閉包的具體定義有不少種說法,這些說法大致能夠分爲兩類:
一種說法認爲閉包是符合必定條件的函數,好比參考資源中這樣定義閉包:閉包是在其詞法上下文中引用了自由變量(注 1)的函數。
另外一種說法認爲閉包是由函數和與其相關的引用環境組合而成的實體。好比參考資源中就有這樣的的定義:在實現深約束(注 2)時,須要建立一個能顯式表示引用環境的東西,並將它與相關的子程序捆綁在一塊兒,這樣捆綁起來的總體被稱爲閉包。javascript

#python 中的閉包
... def func(data):
...     count = [data]
...     def wrap():
...         count[0] += 1
...         return count[0]
...     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 = 0
10.times{|n| sum += n}
print sum

def upto(from,to)
    while from <= to
       yield from
      from+=1
    end
end

upto(1,10) {|n| puts n}


def counter()
  i = 1
  Proc.new{ puts i;i+=1}
end

c = counter()
c.call() 1
c.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);
    }
}
相關文章
相關標籤/搜索