如何允许exec在python的嵌套方法中访问自由变量?

时间:2019-01-02 10:16:27

标签: python python-2.x

我必须在python(2.6)的嵌套方法中访问exec中的自由变量

def outerF():
    la = 5
    def innerF():
        str1 = "print(la)"
        exec (str1) in globals(),locals()
    innerF()
outerF()

预期结果为5,但出现以下错误

  

NameError:未定义名称'la'

3 个答案:

答案 0 :(得分:0)

对于python 2.6

def outerF():
    la={'y': 5} # exec take argu as dict and in 2.6 nonlocal is not working, 
    # have to create dict element and then process it 
    def innerF():

        str1 = "print({})".format(la['y'])
        exec (str1) in globals(),locals()
    innerF()
outerF()

答案 1 :(得分:0)

使用非本地变量来访问嵌套函数中外部函数的变量,如下所示: Python Global, Local and Nonlocal variables

def outerF():
    la = 5
    def innerF():
        nonlocal la    #it let the la variable to be accessed in inner functions.
        str1 = "print(la)"
        exec (str1) in globals(),locals()
    innerF()
outerF()

答案 2 :(得分:0)

请尝试对变量使用非本地语句。 像这样:

def outerF():
    la = 5
    def innerF():
        nonlocal la
        str1 = "print(la)"
        exec (str1) in globals(),locals()
    innerF()
outerF()

更多信息可以在这里找到:Python Global, Local and Nonlocal variables