溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

詳解Python如何進行閉包時綁定變量操作

發(fā)布時間:2020-07-20 16:09:33 來源:億速云 閱讀:146 作者:小豬 欄目:開發(fā)技術(shù)

小編這次要給大家分享的是詳解Python如何進行閉包時綁定變量操作,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。

搞不清楚在閉包(closures)中Python是怎樣綁定變量的

看這個例子:

>>> def create_multipliers():
...   return [lambda x : i * x for i in range(5)]
>>> for multiplier in create_multipliers():
...   print multiplier(2)
...

期望得到下面的輸出:

0

2

4

6

8

但是實際上得到的是:

8

8

8

8

8

實例擴展:

# coding=utf-8
__author__ = 'xiaofu'

# 解釋參考 http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures

def closure_test1():
  """
  每個closure的輸出都是同一個i值
  :return:
  """
  closures = []
  for i in range(4):
    
    def closure():
      print("id of i: {}, value: {} ".format(id(i), i))

    closures.append(closure)

  # 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.

  for c in closures:
    c()

def closure_test2():

  def make_closure(i):

    def closure():
      print("id of i: {}, value: {} ".format(id(i), i))

    return closure

  closures = []

  for i in range(4):
    closures.append(make_closure(i))

  for c in closures:
    c()


if __name__ == '__main__':
  closure_test1()
  closure_test2()

輸出:

id of i: 10437280, value: 3 
id of i: 10437280, value: 3 
id of i: 10437280, value: 3 
id of i: 10437280, value: 3 
id of i: 10437184, value: 0 
id of i: 10437216, value: 1 
id of i: 10437248, value: 2 
id of i: 10437280, value: 3

看完這篇關(guān)于詳解Python如何進行閉包時綁定變量操作的文章,如果覺得文章內(nèi)容寫得不錯的話,可以把它分享出去給更多人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI