国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

Python新手如何進(jìn)行閉包時綁定變量操作

瀏覽:149日期:2022-07-23 18:41:38

搞不清楚在閉包(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

但是實(shí)際上得到的是:

8

8

8

8

8

實(shí)例擴(kuò)展:

# coding=utf-8__author__ = ’xiaofu’# 解釋參考 http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closuresdef 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新手如何進(jìn)行閉包時綁定變量操作的文章就介紹到這了,更多相關(guān)Python閉包時綁定變量實(shí)例內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 甘德县| 兴和县| 临桂县| 麟游县| 浪卡子县| 鹿邑县| 康马县| 改则县| 嘉黎县| 怀来县| 武邑县| 绥德县| 同德县| 阿瓦提县| 南和县| 禄劝| 武宣县| 新蔡县| 徐汇区| 罗平县| 乌兰浩特市| 葫芦岛市| 集贤县| 拜城县| 磐安县| 大姚县| 镶黄旗| 瑞昌市| 黑水县| 青河县| 万全县| 顺义区| 蒲城县| 武胜县| 中卫市| 和政县| 永定县| 苗栗县| 连城县| 额尔古纳市| 吴江市|