簡體   English   中英

python3.6和python3.7的導入區別

[英]Importing difference in python3.6 and python3.7

我對 python3.6 和 python3.7 中的導入有疑問。

我有以下目錄結構:

.
└── lib
    ├── feature
    │   ├── feature1.py
    │   ├── __init__.py
    │   └── new
    │       ├── feature1.py
    │       └── __init__.py
    └── __init__.py

我在文件lib/feature/__init__.py有以下lib/feature/__init__.py

from lib.feature.feature1 import Feature1

我在文件lib/feature/feature1.py有以下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。

提前致謝。

這是一個帶有“別名”導入( import .. as )的錯誤,在 Python 3.7 中得到修復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM