我有以下的文件結構,每個代碼最多一行(如下圖所示)的__init__.py當它是圓形的進口:使用絕對導入和
a
├── b
│ ├── c.py import a.b.d as d
│ ├── d.py
│ └── __init__.py from a.b.c import *
├── __init__.py
└── main.py import a.b as b
通過運行python -m a.main
,我得到以下錯誤:
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/tmp/test/a/main.py", line 1, in <module>
import a.b as b
File "a/b/__init__.py", line 1, in <module>
from a.b.c import *
File "a/b/c.py", line 1, in <module>
import a.b.d as d
AttributeError: 'module' object has no attribute 'b'
我不確定這是否是由循環導入造成的。如果我將import a.b.d as d
更改爲from a.b import d
,則不會再有錯誤。
from'b.py'你應該只能'輸入c'否? –
[This](https://www.youtube.com/watch?v=0oTh1CXRaQ0)雖然有點長,但在處理導入時可能非常有用。 – quapka
@peter我有另一篇文章,涵蓋創建和導入自定義模塊。如果它可以幫助你,請註冊。 http://stackoverflow.com/questions/37072773/how-to-create-and-import-a-custom-module-in-python/37074372#37074372 – PyNoob