【发布时间】:2020-03-12 08:15:31
【问题描述】:
有两个 py 文件。 util.py
def add_sum():
print(x + 3)
test.py
from util import *
x=3
add_sum()
当我运行 test.py 时,出现错误:
Traceback (most recent call last):
File "test.py", line 45, in <module>
add_sum()
File "util.py", line 10, in add_sum
print(x + 3)
NameError: name 'x' is not defined
变量x是全局变量,为什么函数无法到达x并报错?
【问题讨论】:
-
因为它在你的文件中是全局的
-
这能回答你的问题吗? Python importing variables from other file
-
为什么
test.py会导入自己? -
@martineau 已编辑。
-
@ThomasSchillaci 存在一些差异。我可以理解 Python importing variables from other file 。真正要知道的是在import之后,add_sum函数不像在新文件test中定义?
标签: python function import scope