简体   繁体   English

为什么我的班级不能用Python导入?

[英]Why won't my class import in Python?

Edit: __init__.py files are included, but I'm using Python 3 - I don't think it matters. 编辑:包括__init__.py文件,但是我使用的是Python 3-我认为这并不重要。

Another edit: Anything in config.py will import with no problem. 另一个编辑: config.py任何内容都将毫无问题地导入。 If I simply omit from cache import Cache then no errors. 如果我只是from cache import Cache省略from cache import Cache则没有错误。 Interestingly, no errors occur when importing Config in config.py 有趣的是,在config.py导入Config时没有错误发生

I cannot figure out what's wrong here. 我无法弄清楚这里出了什么问题。 I'm getting an error whenever I try to import a specific class. 每当我尝试导入特定的类时,都会出现错误。 Here's what my project layout looks like: 这是我的项目布局:

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

cache.py: cache.py:

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

manager.py manager.py

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

test.py 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()
...

So when I run test.py I get this: 因此,当我运行test.py时,我得到了:

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

ImportError: cannot import name 'Cache'

from manager import Manager line 5, 

Even though config.Config loads just fine, no errors there, but as soon as I try to import cache.Cache it suddenly can't find or import any class in cache.py . 即使config.Config加载正常,也没有任何错误,但是当我尝试导入cache.Cache它突然无法在cache.py找到或导入任何类。 All files have the same permissions. 所有文件具有相同的权限。 Can someone tell me what's wrong here? 有人可以告诉我这是怎么回事吗?

You are missing the __init__.py file in your module 您缺少模块中的__init__.py文件

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

and instead of messing with sys.path should do a relative import like 而不是弄乱sys.path应该做一个相对的导入

from .config import Config
from .cache import Cache

Python 2 may also need a line Python 2可能还需要一行

from __future__ import absolute_import

before those imports. 在那些进口之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM