問題描述
我正在查看 django 中的模型系統(tǒng)是如何工作的,我發(fā)現(xiàn)了一些我不明白的地方.
I'm taking a look at how the model system in django works and I noticed something that I don't understand.
我知道你創(chuàng)建了一個空的 __init__.py
文件來指定當(dāng)前目錄是一個包.并且您可以在 __init__.py
中設(shè)置一些變量,以便 import * 正常工作.
I know that you create an empty __init__.py
file to specify that the current directory is a package. And that you can set some variable in __init__.py
so that import * works properly.
但是django在__init__.py
中添加了一堆from ... import ...語句并定義了一堆類.為什么?這不是讓事情看起來很亂嗎?__init__.py
中是否有需要此代碼的原因?
But django adds a bunch of from ... import ... statements and defines a bunch of classes in __init__.py
. Why? Doesn't this just make things look messy? Is there a reason that requires this code in __init__.py
?
推薦答案
當(dāng)你導(dǎo)入包含它的包(目錄)時,__init__.py
中的所有導(dǎo)入都可用.
All imports in __init__.py
are made available when you import the package (directory) that contains it.
例子:
./dir/__init__.py
:
./test.py
:
忘了提一下,__init__.py
中的代碼在您第一次從該目錄導(dǎo)入任何模塊時運行.所以它通常是放置任何包級初始化代碼的好地方.
forgot to mention, the code in __init__.py
runs the first time you import any module from that directory. So it's normally a good place to put any package-level initialisation code.
dgrant 在我的示例中指出了可能的混淆.在 __init__.py
import something
可以導(dǎo)入任何模塊,不需要從包中導(dǎo)入.例如,我們可以將其替換為 import datetime
,然后在我們的頂級 test.py
中,這兩個片段都可以工作:
dgrant pointed out to a possible confusion in my example. In __init__.py
import something
can import any module, not necessary from the package. For example, we can replace it with import datetime
, then in our top level test.py
both of these snippets will work:
和
底線是:在 __init__.py
中分配的所有名稱,無論是導(dǎo)入的模塊、函數(shù)還是類,在您導(dǎo)入包或包中的模塊時自動在包命名空間中可用.
The bottom line is: all names assigned in __init__.py
, be it imported modules, functions or classes, are automatically available in the package namespace whenever you import the package or a module in the package.
這篇關(guān)于將代碼添加到 __init__.py的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!