gpt4 book ai didi

python - 在 Python 中导入函数

转载 作者:行者123 更新时间:2023-12-01 07:57:31 25 4
gpt4 key购买 nike

如何导入使用当前文件中定义的变量的函数?

ma​​in.py

from functions import a

x = 1

print(a())

函数.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

最佳答案

正如另一个答案所指出的,由于 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

关于python - 在 Python 中导入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55885578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com