如何从内部函数更改函数范围中的变量

时间:2020-06-06 14:40:29

标签: python

相同的代码将在JS中工作,但在python中将不会更改变量,如何在嵌套函数中更改变量?在此先感谢您,并为菜鸟提出的问题表示歉意

   def sample():
       a = False
       def sample2():
           a = True
       sample2()
       return a

3 个答案:

答案 0 :(得分:2)

使用非本地变量修改函数范围之外的变量。

   def sample():
       a = False
       def sample2():
           nonlocal a
           a = True
       sample2()
       return a

答案 1 :(得分:1)

使用nonlocal

def sample():
    a = False
    def sample2():
        nonlocal a
        a = True
    sample2()
    return a

Python 3 docs

非本地语句使列出的标识符引用到最近的封闭范围(不包括全局变量)中的先前绑定变量

答案 2 :(得分:1)

 def sample():
       a = False
       def sample2():
           nonlocal a
           a = True
       sample2()
       return a

这应该有效。