码迷,mamicode.com
首页 > 编程语言 > 详细

python闭包

时间:2018-01-27 20:23:12      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:www   参考   count   www.   turn   body   htm   返回   python   

参考来自:http://www.jb51.net/article/65478.htm

def createCounter():
    s = [0]
    def counter():
        s[0] = s[0] + 1
        print(s)
        return s[0]

    return counter

counterA = createCounter()

print(counterA(),counterA(),counterA(),counterA())


输出:
[1]
[2]
[3]
[4]
1 2 3 4

 当返回函数引用了循环变量或者后续会发生变化的变量时,这个变量会一直跟随该返回函数

python闭包

标签:www   参考   count   www.   turn   body   htm   返回   python   

原文地址:https://www.cnblogs.com/liuw-flexi/p/8366660.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!