如何访问闭包内的外部函数变量(python 2.6)?

时间:2010-09-11 19:32:05

标签: python django python-3.x python-2.6 python-nonlocal

来自wikipedia

我需要以与使用python 3.x中的'nonlocal'关键字类似的方式访问外部函数变量。有没有办法在python 2.6中做到这一点? (不一定使用nonlocal关键字)

1 个答案:

答案 0 :(得分:5)

在这种情况下,我总是使用辅助对象:

def outerFunction():
    class Helper:
        val = None
    helper = Helper()

    def innerFunction():
        helper.val = "some value"

当你启动一个应该将值写入外部函数作用域的新线程时,这也会派上用场。在这种情况下,helper将作为参数传递给innerFunction(线程的函数)。