将代码添加到__init__.py [英] Adding code to __init__.py
问题描述
我正在研究django中的模型系统如何工作,我注意到一些我不理解的东西.
I'm taking a look at how the model system in django works and I noticed something that I don't understand.
我知道您创建了一个空的__init__.py
文件来指定当前目录是一个包.并且您可以在__init__.py
中设置一些变量,以便导入*正常工作.
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添加了一堆from ... import ...语句,并在__init__.py
中定义了一堆类.为什么?这不仅会使事情看起来凌乱吗?有没有必要在__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
?
推荐答案
__init__.py
中的所有导入在导入包含它的软件包(目录)时都可用.
All imports in __init__.py
are made available when you import the package (directory) that contains it.
示例:
./dir/__init__.py
:
import something
./test.py
:
import dir
# can now use dir.something
忘记了,__init__.py
中的代码在您首次从该目录导入任何模块时运行.因此,通常是放置任何程序包级初始化代码的好地方.
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
可以导入任何模块,而不必从包中导入.例如,我们可以将其替换为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:
import dir
print dir.datetime.datetime.now()
和
import dir.some_module_in_dir
print dir.datetime.datetime.now()
最重要的是:在__init__.py
中分配的所有名称(无论是导入的模块,函数还是类),只要在导入软件包或软件包中的模块时都可以在软件包名称空间中自动获得.
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.
这篇关于将代码添加到__init__.py的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!