python 应用于循环的闭包中的Python范围怪癖

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 应用于循环的闭包中的Python范围怪癖相关的知识,希望对你有一定的参考价值。

# python closures close over variables, not values
funcs = []
for i in range(4):  # `i` is actually created at the top of the enclosing function, only once
    # `i` has a new value assigned to it here
    def f():
        # Each incarnation of this function closes over the SAME VARIABLE, `i`
        print i
    funcs.append(f)

for f in funcs:
    f()
    
# prints 4 times 3


# SOLUTION 1
# factory function, because python scopes over functions
def make_f(i):
    def f():
        print i
    return f

funcs = []
for i in range(4):
    funcs.append(make_f(i))


# SOLUTION 2
# default values, because they are bound by value to the function
# just once the function is defined
# It is the same problem of the mutable argument f(a={}) or f(a=[]) which is going to be always the same
funcs = []
for i in range(4):
    def f(i=i):
        print i
    funcs.append(f)



以上是关于python 应用于循环的闭包中的Python范围怪癖的主要内容,如果未能解决你的问题,请参考以下文章

等效于 Javascript 中的 python 范围 [重复]

Python 应用闭包思路动态生成unittest执行脚本---分析问题,解决问题,记录填坑。

python开发装饰器的应用

python中的闭包

Python中的闭包

Python--高阶函数函数嵌套名称空间及变量作用域闭包装饰器