我对python3.6和python3.7中的导入有疑问。
我具有以下目录结构:
.
└── lib
├── feature
│ ├── feature1.py
│ ├── __init__.py
│ └── new
│ ├── feature1.py
│ └── __init__.py
└── __init__.py
文件lib/feature/__init__.py
中包含以下内容:
from lib.feature.feature1 import Feature1
文件lib/feature/feature1.py
中包含以下内容:
import lib.feature.new.feature1 as new
class Feature1: pass
要重新创建我的环境,可以使用以下命令:
mkdir lib
touch lib/__init__.py
mkdir -p lib/feature/new
echo "from lib.feature.feature1 import Feature1" > lib/feature/__init__.py
echo -e "import lib.feature.new.feature1 as new\nclass Feature1: pass" > lib/feature/feature1.py
touch lib/feature/new/__init__.py
touch lib/feature/new/feature1.py
当我使用python3.7运行此代码时,它可以很好地工作。当我使用python3.6运行此代码时,出现以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "***/import_test/lib/feature/__init__.py", line 1, in <module>
from lib.feature.feature1 import Feature1
File "***/import_test/lib/feature/feature1.py", line 2, in <module>
import lib.feature.new.feature1 as new
AttributeError: module 'lib' has no attribute 'feature'
所以我的问题是,当您使用python3.6或python3.7运行代码时,为什么会有不同的结果?
为解决此问题,我将lib/feature/feature1.py
中的导入更改为:
from .new import feature1 as new
要测试,我只是转到python并尝试导入模块:
import_test$ python
Python 3.6.8 (default, Dec 25 2018, 00:00:00)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import lib.feature
更改后,它也适用于python3.6。
谢谢。