python - 从另一个文件导入变量时出错
问题描述
我正在构建一个使用非常大变量的程序,所以我给它自己的文件。尝试导入变量时,我不断收到错误。
假设file1
有我的代码和file2
变量,我file2
看起来像这样:
array = [[0,0,0],[0,0,0],[0,0,0]]
我file1
看起来像这样:
import tkinter
import file2
class test:
def print_var():
print(file2.array)
test().print_var()
每当我运行它时,它都会告诉我'module' object does not have attribute 'array'
. 我尝试将它放在课堂上并导入课堂,但这也不起作用。感觉就像我错过了一些重要的东西,任何帮助将不胜感激。
如果重要的话:变量是一个数组,文件在同一个文件夹中,并且项目正在使用 tkinter。
编辑:这个项目由 3 个文件组成:一个main
文件,变量 file( file2
),file1
它被导入到main
. main
文件和file1
导入,这file2
会导致问题吗?
编辑 2:作为对 Mike 的回应,引用了实际代码,但是我不想使用实际代码,因为我认为将 300 行代码转储到这里会令人不悦。我已经改变了我的例子来反映你的建议。
编辑3:我将__init__.py
文件放入文件夹无济于事。
编辑4:回应迈克的评论。好点子。很抱歉我没有提供足够的信息,我试图只包含必要的信息,但显然我错过了很多。下次我一定会提供更好的上下文。
解决方案
你所描述的应该有效。这是一个工作示例:
+
- file1.py
- file2.py
#file1.py
array = ['x', 'y']
#file2.py
import file1
print(file1.array)
# this also works
from file1 import array
print(array)
# Bash
❯❯❯ python file2.py
['x', 'y']
['x', 'y']
与导入错误相关的属性错误的常见原因:
名称冲突(例如,您有一个文件夹和一个同名的文件,并且正在导入错误的文件)
循环导入(file1 导入 file2,但 file2 也导入 file1)
要解决此问题,您可以尝试:
# Ensure correct file is being imported
>>> print(file2.__file__)
'~/dev/file2.pyc'
# Check the variables in the imported module's scope - note 'array' is listed
>>> dir(file2)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'array']
- 确保没有循环导入 - 如果
__init__.py
涉及,您必须格外小心,因为其中的代码将在使用父文件夹时运行。这可能会导致代码比您想象的更早导入
循环进口注意事项
如果我在上面的工作代码示例中包含循环导入,请注意我得到的错误与您得到的完全相同:
#file1.py
import file2 # Circular Import
array = ['x', 'y']
#file2.py
import file1
print(dir(file1))
print(file1.array)
# Bash - Note unlike example above, "array" is not included
# in the module's scope due to the circular import
❯❯❯ python file2.py
['__builtins__', '__doc__', '__file__', '__name__', '__package__']
Traceback (most recent call last):
...
AttributeError: 'module' object has no attribute 'array'
推荐阅读
- javascript - JavaScript - 按值和最多两个级别对数组进行分组
- amazon-web-services - 如何通过 Web 浏览器(不是控制台)使用 Amazon S3 存储桶
- php - 在 WooCommerce 的电子邮件中在表格下方重复的订单项目名称
- python-3.x - 在循环 Python 中创建对象——令人费解的行为
- unity3d - 如何在 Unity Shader 中缩放图像而不模糊?
- awk - 在没有循环的情况下检查 AWK 中的关联数组中是否存在值
- angular - 导入“anychart”打字稿
- php - 我需要帮助才能在 php 中建立联系
- python - TypeError:“NoneType”对象不可迭代:3 和 5 的倍数
- java - 有谁知道在java中单击按钮时如何从其他类运行方法