簡體   English   中英

為什么我的班級不能用Python導入?

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

編輯:包括__init__.py文件,但是我使用的是Python 3-我認為這並不重要。

另一個編輯: config.py任何內容都將毫無問題地導入。 如果我只是from cache import Cache省略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

manager.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文件

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

在那些進口之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM