django 项目中的许多目录都包含一个 __init__.py
,我认为它将用作某些东西的初始化。这个__init__.py
用在什么地方?
最佳答案
Python 并不认为 sys.path
中每个目录的每个子目录都必须是一个包:只有那些具有名为 __init__.py
。考虑以下 shell session :
$ mkdir adir
$ echo 'print "hello world"' > adir/helo.py
$ python -c 'import adir.helo'
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named adir.helo
$ touch adir/__init__.py
$ python -c 'import adir.helo'
hello world
看到了吗?只有目录 adir
和模块 helo.py
在其中,尝试 import adir.helo
失败。如果 __init__.py
也存在于 adir
中,那么 Python 知道 adir
是一个包,因此导入成功。
关于python - 为什么 django 包含很多 '__init__.py' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1988149/