Python新手如何進(jìn)行閉包時(shí)綁定變量操作
搞不清楚在閉包(closures)中Python是怎樣綁定變量的
看這個(gè)例子:
>>> 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
但是實(shí)際上得到的是:
8
8
8
8
8
實(shí)例擴(kuò)展:
# coding=utf-8 __author__ = 'xiaofu' # 解釋參考 http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures def closure_test1(): """ 每個(gè)closure的輸出都是同一個(gè)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新手如何進(jìn)行閉包時(shí)綁定變量操作的文章就介紹到這了,更多相關(guān)Python閉包時(shí)綁定變量實(shí)例內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
CentOS7上使用pyenv搭建Django環(huán)境
本文主要介紹了CentOS7上使用pyenv搭建Django環(huán)境,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11python3 unicode列表轉(zhuǎn)換為中文的實(shí)例
今天小編就為大家分享一篇python3 unicode列表轉(zhuǎn)換為中文的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-10-10Python?matplotlib的spines模塊實(shí)例詳解
作為程序員,經(jīng)常需要進(jìn)行繪圖,下面這篇文章主要給大家介紹了關(guān)于Python?matplotlib的spines模塊的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08python 接口實(shí)現(xiàn) 供第三方調(diào)用的例子
今天小編就為大家分享一篇python 接口實(shí)現(xiàn) 供第三方調(diào)用的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-08-08Pythony運(yùn)維入門之Socket網(wǎng)絡(luò)編程詳解
這篇文章主要介紹了Pythony運(yùn)維入門之Socket網(wǎng)絡(luò)編程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04pytorch 如何使用batch訓(xùn)練lstm網(wǎng)絡(luò)
這篇文章主要介紹了pytorch 如何使用batch訓(xùn)練lstm網(wǎng)絡(luò)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05python+requests實(shí)現(xiàn)接口測(cè)試的完整步驟
這篇文章主要給大家介紹了關(guān)于python+requests實(shí)現(xiàn)接口測(cè)試的完整步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10python實(shí)現(xiàn)微信跳一跳輔助工具步驟詳解
這篇文章主要介紹了python實(shí)現(xiàn)微信跳一跳輔助工具的步驟詳解以及使用說明,需要的朋友可以參考下2018-01-01