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

标签 python django module

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/

相关文章:

python - 我是否正确使用 ctypes 来 pythonify 这个结构?

mysql - 全局单个元素的最佳数据库实践?

python - 在 django 中自动给出职位名称

Android Studio 模块无法解析符号上下文

r - 在 Shiny 模块中使用模态窗口

python - Django,如何通过模型字段访问模型内​​部的模型

python - Azure 应用服务上的 FastAPI-Docker 镜像引发 [CRITICAL] 工作超时

python - ValueError : Graph disconnected: cannot obtain value for tensor Tensor. ..可以毫无问题地访问以下前几层:[]

html - 何时在 Django 中使用 as_hidden,为什么不只显示 : none; in CSS?

python - 如何从python中的不同文件夹导入类?