了解Python闭包

muf*_*fel 7 python closures scope python-2.7

我一直认为Python 2.7函数引用它们所定义的范围.请考虑以下代码.为什么第二个输出不是"计算:罪"?

有没有办法修改代码,以便它按预期工作?

import math

mymath = dict()

for fun in ["sin", "cos"]:
    def _impl(val):
        print "calculating: %s" % fun
        return getattr(math, fun)(val)
    mymath[fun] = _impl

# calculating: cos
print mymath["cos"](math.pi)

# calculating: cos <- why?
print mymath["sin"](math.pi)
Run Code Online (Sandbox Code Playgroud)

Ion*_*lub 8

fun调用函数时会计算值.

在您提供的示例中,fun是一个全局变量,它在for循环运行后的值为"cos" .

我认为你期望在fun创建函数时替换值,但事实并非如此.该函数在运行时就像它应该的那样运行时计算变量的值.

它不是您定义函数的命名空间,而是您运行该函数的命名空间.

import math

mymath = dict()

for fun in ["sin", "cos"]:
    def _impl(val):
        print "calculating: %s" % fun
        return getattr(math, fun)(val)
    mymath[fun] = _impl


fun = 'tan'
# will print and calculate tan
print mymath["cos"](math.pi)
Run Code Online (Sandbox Code Playgroud)