【发布时间】:2020-03-04 13:56:02
【问题描述】:
我正在编写代码生成器并希望能够导出到不同的文件类型。 foo 模块包含不同类(subA、subA、subC)的 sn-ps。 bar.py 和 baz.py 持有不同语言的 sn-ps。
我发现导入foo.bar 并获取bar 语言的所有sn-ps 比必须为每个类导入bar 更方便。
同样,我宁愿将特定类的所有 sn-ps 放在同一目录中,因此有以下组织
foo
| __init__.py
+ subA
| | __init__.py
| | bar.py
| ` baz.py
+ subB
| | __init__.py
| | bar.py
| ` baz.py
` subC
| __init__.py
| bar.py
` baz.py
我希望能够像这样导入:
from foo.bar import subA 应该让我访问foo/subA/bar.py
我认为我需要在 foo/__init__.py 中进行重新组织,但我不知道具体要做什么。我的猜测是我需要创建一个空模块或命名空间,甚至只是我用所需模块填充的对象。
但我不断收到语法错误。
目前我的foo/__init__.py 看起来像这样
import foo.subA.bar
import foo.subB.bar
import foo.subC.bar
class bar:
def __init__(self):
self.subA = foo.subA.bar
self.subB = foo.subB.bar
self.subC = foo.subC.bar
这让我可以导入 foo 和 foo.bar 但尝试访问
foo.bar.subA给我
AttributeError: type object 'bar' has no attribute 'subA'
我不确定我在这里缺少什么,所以我愿意接受建议。
【问题讨论】: