問題描述
以下代碼有效:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
但是,以下內容:
import sqlalchemy
Base = sqlalchemy.ext.declarative.declarative_base()
拋出:模塊sqlalchemy"沒有屬性ext"
.怎么可能?
推薦答案
sqlalchemy
是一個包,導入一個包并不會自動加載它的子模塊.當你這樣做時
sqlalchemy
is a package, and importing a package doesn't automatically load its submodules. When you do
import sqlalchemy
Base = sqlalchemy.ext.declarative.declarative_base()
導入系統(tǒng)不會加載 sqlalchemy.ext
子模塊,因為您沒有要求它.
The import system doesn't load the sqlalchemy.ext
submodule, because you didn't ask for it.
當你這樣做時
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
您已明確要求加載 sqlalchemy.ext
和 sqlalchemy.ext.declarative
,因此訪問有效.
You've explicitly requested that sqlalchemy.ext
and sqlalchemy.ext.declarative
get loaded, so the access works.
你也可以這樣做
import sqlalchemy.ext.declarative
Base = sqlalchemy.ext.declarative.declarative_base()
這也將加載 sqlalchemy.ext
和 sqlalchemy.ext.declarative
.
有些包會在 __init__.py
中自動加載其子模塊,因此您不必顯式導入子模塊.不過,這不是您應該依賴的東西.
Some packages automatically load their submodules inside their __init__.py
, so you don't have to import submodules explicitly. This isn't something you should rely on, though.
這篇關于Python 命名空間“導入 X"和“從 X 導入"的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!