Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 嵌套函数和父变量?_Python - Fatal编程技术网

Python 嵌套函数和父变量?

Python 嵌套函数和父变量?,python,Python,当我运行下面的代码时: def run(): test = False def tester(): if not test: print("test is false") else: print("test is true") test = not test tester() run() 我得到一个错误: 赋值前引用的局部变量“test” 我的印象是子函数可以访问父函数变量。在玩了一会儿这段代码之后,我发现如果我删除了赋值(test=

当我运行下面的代码时:

def run():
  test = False
  def tester():
    if not test:
      print("test is false")
    else:
      print("test is true")
    test = not test
  tester()
run()
我得到一个错误:

赋值前引用的局部变量“test”

我的印象是子函数可以访问父函数变量。在玩了一会儿这段代码之后,我发现如果我删除了赋值(
test=nottest
),那么一切都正常


为什么在子函数中赋值会破坏此代码?如果我不应该在子函数中赋值,那么切换
test
标志的最佳方式是什么?我是否应该从子函数返回一个值并使用它来切换
test

Python 2不支持对嵌套函数关闭的变量赋值。通常的解决方法是将值放在可变容器中(例如,一个元素列表)。Python3为此提供了
nonlocal
关键字。

因为编译器/解释器在
tester
函数中检测到赋值,
test
成为局部变量。然后,在
if
语句中自然没有赋值。您是否尝试过
非本地测试
?应该可以帮助您。使用
非局部
与使用全局变量类似吗?我听说在这样的事情上使用全局变量通常是不好的做法-使用
非局部
也是不好的做法吗?
非局部
的socpe是函数,但不是全局的,所以我认为它不像
全局
那样是不好的做法。