[英]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.