gpt4 book ai didi

python - python 在什么时候以及多久执行一次 __init__.py 文件

转载 作者:太空狗 更新时间:2023-10-29 17:17:50 25 4
gpt4 key购买 nike

有人可以帮忙澄清一下,当使用 import 命令时,此时会执行各种包目录中的 __init__.py 文件?

  1. 对于每个包含的模块?
  2. 仅在第一个 import 命令中执行一次?
  3. 对于每个 import 命令?

最佳答案

它在第一个模块导入时被评估。在下一次导入时,解释器检测到该模块已经加载并简单地返回对它的引用。无需重新执行代码。

引用 The import system :

关于缓存模块:

The first place checked during import search is sys.modules. This mapping serves as a cache of all modules that have been previously imported, including the intermediate paths. So if foo.bar.baz was previously imported, sys.modules will contain entries for foo, foo.bar, and foo.bar.baz. Each key will have as its value the corresponding module object.

During import, the module name is looked up in sys.modules and if present, the associated value is the module satisfying the import, and the process completes. However, if the value is None, then an ImportError is raised. If the module name is missing, Python will continue searching for the module.

导入时执行__init__:

Python defines two types of packages, regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an init.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The __init__.py file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.

关于python - python 在什么时候以及多久执行一次 __init__.py 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39452319/

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