我必须在python(2.6)的嵌套方法中访问exec
中的自由变量
def outerF():
la = 5
def innerF():
str1 = "print(la)"
exec (str1) in globals(),locals()
innerF()
outerF()
预期结果为5,但出现以下错误
NameError:未定义名称'la'
答案 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