gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:15:41 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com