如何使用已导入的变量?

保罗·韦尔西亚

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

我有一个空的init .py文件; 所有文件init,module1和module2都位于同一文件夹中。该文件夹在sys.path中可见。从x导入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)

module1已运行,但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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章