我正在导入一个包foo1.foo2
,其__init__.py
正在导入一个子模块foo1.foo2.foo3.bar1
,这是一个文件。如果我尝试在该文件中导入foo1.foo2.foo3.bar2
,则会收到以下错误:
AttributeError: module 'foo1' has no attribute 'foo2'
既然不鼓励使用相对导入,如何在不使用相对导入的情况下解决此问题?
这是我拥有的包结构和文件内容:
/
├── foo1
│ ├── __init__.py:
│ └── foo2
│ ├── __init__.py: "import foo1.foo2.foo3.bar1"
│ └── foo3
│ ├── __init__.py
│ ├── bar1.py: "import foo1.foo2.foo3.bar2 as bar2"
│ └── bar2.py:
└── main.py: "import foo1.foo2"
运行python main.py
会生成以下错误:
Traceback (most recent call last):
File "main.py", line 1, in <module>
import foo1.foo2
File "/foo1/foo2/__init__.py", line 1, in <module>
import foo1.foo2.foo3.bar1
File "/foo1/foo2/foo3/bar1.py", line 1, in <module>
import foo1.foo2.foo3.bar2 as bar2
AttributeError: module 'foo1' has no attribute 'foo2
我正在使用Python 3.6.0 :: Anaconda 4.3.1
.
谢谢!
将import foo1.foo2.foo3.bar2 as bar2
更改为from foo1.foo2.foo3 import bar2
。
然后它起作用了。