首页 > 解决方案 > 从另一个文件导入变量时出错

问题描述

我正在构建一个使用非常大变量的程序,所以我给它自己的文件。尝试导入变量时,我不断收到错误。

假设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:回应迈克的评论。好点子。很抱歉我没有提供足够的信息,我试图只包含必要的信息,但显然我错过了很多。下次我一定会提供更好的上下文。

标签: pythonarrayspython-3.xtkinter

解决方案


你所描述的应该有效。这是一个工作示例:

+
- 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'

推荐阅读