这是我的文件夹结构:
storage/
__init__.py - contains class StorageAbstract, class DummyStorage, class STORE_TYPE
file.py - contains class FileStorage
db/
__init__.py - contains class DbStorage, class DbStorageAbstract
pg.py - contains class PgStorage
sqlite.py - contains class SQLiteStorage
类 PgStorage 和 SQLiteStorage 继承自 DbStorageAbstract,因此我需要导入它。我这样做(在 pg.py 和 sqlite.py 中):
from . import DbStorageAbstract
这会引发以下错误:
ImportError: cannot import name 'DbStorageAbstract'
但是,当我从 storage/db/__init__py 移动 DbStorageAbstract 时。到 storage/__init__py 并像这样导入它:
from .. import DbStorageAbstract
然后就可以正常工作了。我已阅读this , this和许多其他资源,但仍然无法找出导致问题的原因。如果是循环依赖,那么将类移动到另一个文件将无济于事。
如果需要更多信息,请在评论中告诉我,我将编辑问题。
我使用的是Python 3.5
编辑:
尽管此问题已被确定为可能与 this question 重复我不明白它如何回答我的问题。与其他问题不同,我在每个文件夹中已经有 init 文件。如果我错了,请指出我在哪里可以找到答案。
编辑2: 这是 db/init.py 文件:
##################################################################
# Copyright 2018 Open Source Geospatial Foundation and others #
# licensed under MIT, Please consult LICENSE.txt for details #
##################################################################
#import sys
#sys.path.append("/mnt/c/Users/Jan/Documents/GitHub/pywps")
import logging
from abc import ABCMeta, abstractmethod
from pywps import configuration as config
from .. import StorageAbstract
from . import sqlite
from . import pg
LOGGER = logging.getLogger('PYWPS')
class DbStorageAbstract(StorageAbstract):
"""Database storage abstract class
"""
__metaclass__ = ABCMeta
@abstractmethod
def store(self, output):
pass
@abstractmethod
def store_output(self, file_name, identifier):
pass
class DbStorage(StorageAbstract):
def __init__(self):
self.storage = self.get_db_type()
def store(self, output):
assert(self.storage is not None)
self.storage.store(output)
def get_db_type(self):
# get db_type from configuration
try:
db_type = config.get_config_value('db', 'db_type')
except KeyError:
raise exception("Database type has not been specified")
# create an instance of the appropriate class
if db_type == "PG":
storage = pg.PgStorage()
elif db_type == "SQLITE":
storage = sqlite.SQLiteStorage()
else:
raise exception("Unknown database type: '{}'".format(db_type))
return storage
最佳答案
导入发生在类定义之前。在db/__init__.py
中,您正在导入pg.py、sqlite.py
,它们取决于此处定义的类。要解决此问题,请将 DbStorageAbstract 移动到另一个文件,如果您要在与 pg.py、sqlite.py 相同的文件中使用它,请确保导入将是像这样:
from . import dbstorage # this file is the new one contains DbStorageAbstract class
from . import pg, sqlite
请注意,如果两个模块相互依赖,请尝试创建第三个模块,以便解决此问题。
关于python - 无法从子文件夹中的 __init__ 导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50728439/