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

 闭包是一种程序结构,内部函数可以引用外部函数的参数和局部变量 

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

posted @ 2018-01-27 17:38  liuw_flexi  阅读(130)  评论(0编辑  收藏  举报