如何导入使用当前文件中定义的变量的函数?
main.py
from functions import a
x = 1
print(a())
functions.py
def a():
return x
错误消息
Traceback (most recent call last):
File "c:\Users\Test\.vscode\extensions\ms-python.python-2019.4.11987\pythonFiles\ptvsd_launcher.py", line 43, in <module>
main(ptvsdArgs)
File "c:\Users\Test\.vscode\extensions\ms-python.python-2019.4.11987\pythonFiles\lib\python\ptvsd\__main__.py", line 410, in main
run()
File "c:\Users\Test\.vscode\extensions\ms-python.python-2019.4.11987\pythonFiles\lib\python\ptvsd\__main__.py", line 291, in run_file
runpy.run_path(target, run_name='__main__')
File "C:\Users\Test\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File "C:\Users\Test\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "C:\Users\Test\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "c:\Users\Test\Google Drive\Dev\Test\main.py", line 5, in <module>
print(a())
File "c:\Users\Test\Google Drive\Dev\Test\functions.py", line 2, in a
return x
NameError: name 'x' is not defined
答案 0 :(得分:1)
正如另一个答案指出的那样,由于Python如何对变量进行作用域作用,因此这将行不通。
因此,我建议您将所有这些变量都移到单独的文件中,例如constants.py
:
main.py
from functions import a
print(a())
constants.py
X = 1
functions.py
from constants import X
def a():
return X
然后,运行import main
将打印1
。
答案 1 :(得分:0)
没有进程范围的全局变量,只有模块级的全局变量。在任何被称为 的全局范围内,a
使用functions.x
,而不使用x
。
import functions
from functions import a, b, c
functions.x = 1
functions.y = 2
functions.z = 3
print(a())
print(b())
print(c())
由于Python具有词法范围,因此每个函数都保留对其定义的全局范围的引用。名称查找使用该作用域来解析自由变量。