Skip to main content
 首页 » 编程设计

python之如何使用已导入的变量

2024年11月24日11zhoujg

我正在尝试从另一个模块导入变量。我的愿望是使用“导入模块”方式而不是“from x import y”方式。 导入行有效,但在尝试从源模块打印变量时出现错误。

我有一个空的 init.py 文件;所有文件 init、module1 和 module2 都在同一个文件夹中。该文件夹在 sys.path 中可见。 使用 from x import y 有效。我只想使用导入模块。 我错过了什么?

module1.py:

X=8 
List=[8,2,9] 
ListOfStrings=["Champa","Lampa", "Dampa"] 
All=[X, List, ListOfStrings, String] 
 
print(All)\ 

module2.py:

import module1 
import sys 
for p in sys.path: 
    print(p) 
 
print(X) 

模块 1 已运行,但 X 显示为未定义。

结果:

[8, [8, 2, 9], ['Champa', 'Lampa', 'Dampa'], 'This is a string'] 
theactualpath\Desktop\Work Excercises\py_test 
Traceback (most recent call last): 
  File "theactualpath\Desktop\Work Excercises\py_test\module2.py", line 6, in <module> 
    print(X) 
NameError: name 'X' is not defined 
[Finished in 0.1s with exit code 1] 
[shell_cmd: python -u "theactualpath\Desktop\Work\Excercises\py_test\module2.py"] 
[dir: theactualpath\Desktop\Work Excercises\py_test] 
[path: various paths from my computer, not the current working folder thou] 

请您参考如下方法:

你有两个选择。

引用 module1 命名空间:

import module1 
... 
print(module1.X) 

将 module1 中的所有内容(或您需要的任何内容)带入您的 module2 命名空间:

from module1 import * # or just import  whatever you need: from module1 import X 
... 
print(X)