【问题标题】:Why won't my class import in Python?为什么我的课程不能在 Python 中导入?
【发布时间】:2017-03-15 14:27:33
【问题描述】:

编辑: __init__.py 文件已包含在内,但我使用的是 Python 3 - 我认为这并不重要。

另一个编辑: config.py 中的任何内容都将毫无问题地导入。如果我只是省略from cache import Cache,那么就没有错误。有趣的是,在config.py中导入Config时没有出现错误

我无法弄清楚这里出了什么问题。每当我尝试导入特定类时都会出错。这是我的项目布局:

app/
    dir1/
        config.py
        cache.py
        manager.py
        __init__.py
    test/
        test.py
        __init__.py

cache.py:

import sys
import os
sys.path.append(os.path.dirname(__file__))
from manager import Manager, AnotherClass
from config import Config

ma​​nager.py

import sys
import os
sys.path.append(os.path.dirname(__file__))
from config import Config
from cache import Cache

test.py

cwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.abspath(os.path.join(cwd, os.pardir)) + '/dir1')
from cache import Cache, AnotherClass
from manager import Manager
test = Cache()
...

所以当我运行 test.py 时,我得到了这个:

File "/path/to/project/app/dir1/<module>
from cache import Cache

ImportError: cannot import name 'Cache'

from manager import Manager line 5, 

尽管config.Config 加载得很好,那里没有错误,但是当我尝试导入cache.Cache 时,它突然无法在cache.py 中找到或导入任何类。所有文件都具有相同的权限。谁能告诉我这里出了什么问题?

【问题讨论】:

  • 模块中没有__init__.py 文件。
  • 您应该检查该目录是否已经在 sys.path 中。这只是一个简单的列表,如果你继续添加它,它会变得非常大。
  • os.path.abspath(os.path.join(cwd, os.pardir)) + '/dir1' 应该是 os.path.abspath(os.path.join(cwd, os.pardir, 'dir1')) - os.path.join 可以接受任意数量的参数。
  • @MartinBonner 在这些情况下,您根本不应该修改 sys.path

标签: python python-import python-module


【解决方案1】:

您的模块中缺少__init__.py 文件

app/
    __init__.py
    dir1/
        __init__.py
        config.py
        cache.py
        manager.py
    test/
        test.py

而不是搞乱sys.path 应该像这样进行相对导入

from .config import Config
from .cache import Cache

Python 2 可能还需要一行

from __future__ import absolute_import

在这些导入之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2021-10-20
    相关资源
    最近更新 更多