Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/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_Import_Scope - Fatal编程技术网

Python 导入函数时出现作用域错误

Python 导入函数时出现作用域错误,python,import,scope,Python,Import,Scope,假设我们将以下内容保存到名为test.py的Python文件中: x = 14 def print_x(): print x def increment_x(): x += 1 然后从同一目录中的交互式Python shell运行以下命令: from test import print_x, increment_x print_x() increment_x() print x 为什么第三次调用会产生错误?前两个函数是否需要定义x才能工作?函数不会抛出错误,因为它们仍然

假设我们将以下内容保存到名为
test.py
的Python文件中:

x = 14

def print_x():
    print x

def increment_x():
    x += 1
然后从同一目录中的交互式Python shell运行以下命令:

from test import print_x, increment_x

print_x()
increment_x()
print x

为什么第三次调用会产生错误?前两个函数是否需要定义
x
才能工作?

函数不会抛出错误,因为它们仍然存在于模块测试中,并且在模块测试中仍然可以看到x。当您将对函数的引用导入到其他位置时,它不会真正移动,也不会与其原始上下文断开连接。如果是这样的话,模块就没有多大用处了

之所以会收到范围错误消息,是因为
x
仅在
test.py
中是全局的,并且当您执行以下操作时:

from test import print_x, increment_x
实际上,您并没有将x导入第二个脚本的全局范围

因此,如果要在第二个脚本中也使x全局化,请执行以下操作:

from test import *
尝试使用IDLE中的调试器实用程序查看
x
何时为
GLOBAL
和何时为AFAIK
increment\u x()
也必须抛出错误