Python包混淆;从包裹进口*

时间:2013-12-27 20:45:16

标签: python module

我正在开发具有以下结构的Flask应用程序:

src
├── config.yaml
├── requirements.txt
├── run.py
└── vortex
    ├── db.py
    ├── __init__.py
    ├── models
    │   ├── computer.py
    │   ├── image.py # Contains a class named Image
    │   └── __init__.py
    ├── templates
    │   └── ...
    └── views.py

modals/__init__.py

from .computer import Computer
from .image import Image

modals/computer.py

from vortex.models import *

i = Image(...)

但不知何故,我无法访问modals/computer.py中的Image类,但文档说,如果我不使用__all__;应导入__init__.py中定义的所有名称。导致循环导入会导致问题吗?

我做错了什么,如何在程序的其他部分使用模型中定义的所有类?

编辑:

追溯:

  ...
  File "..../src/vortex/models/computer.py", line 35, in image
    return Image.find_by_id(self._fields.image)
NameError: global name 'Image' is not defined

1 个答案:

答案 0 :(得分:0)

如果您在computer.py并想要从同一个包中导入其他内容,只需使用相对导入:

from .image import Image

如果您希望能够在一个地方导入大量内容,请使用您的导入创建文件allModels.py,然后执行from .allModels import *。有关如何/为何相对导入__init__.py尴尬的信息,请参阅this question