我一直认为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)

最佳答案

调用该函数时,将评估fun的值。

在您提供的示例中,fun是全局变量,在for循环运行后,其值为“cos”。

我认为您希望在创建函数时替换fun的值,但事实并非如此。该函数在按预期方式运行时会评估该变量的值。

这与定义函数的 namespace 无关,而与运行函数的 namespace 有关。

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)

关于python - 了解Python闭包,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30298220/

10-12 12:55