为什么django包含很多'__init__.py'?

zjm*_*126 3 python django module

django项目中的许多目录包含一个__init__.py,我认为它将用作某些东西的初始化.这在哪里__init__.py使用?

Ale*_*lli 11

Python不会将每个目录的每个子目录都包含在sys.path一个包中:只有那些带有文件的__init__.py.考虑以下shell会话:

$ 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
Run Code Online (Sandbox Code Playgroud)

看到?只有目录adir和模块helo.py,尝试import adir.helo失败.如果__init__.py也存在adir, Python知道这adir是一个包,因此导入成功.


Nic*_*sta 7

你的问题不明确.你到底在问什么?

该文件__init__.py在那里,因此您的文件夹可以定义为一个包,它允许您执行以下操作:

from myapp.models import Something
Run Code Online (Sandbox Code Playgroud)