用Python导入函数

时间:2019-04-27 22:59:12

标签: python module python-import

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

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

2 个答案:

答案 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具有词法范围,因此每个函数都保留对其定义的全局范围的引用。名称查找使用该作用域来解析自由变量。