首页 > 解决方案 > 将名称附加到许多 __init__*.py 是如何工作的?

问题描述

我正在分析其中包含两个类似 init 的文件的 python 代码。名称是__init__solvers.py并且__init__cases.py它们包含典型的__init__.py结构和初始化数据。例如,__init__solvers.py包含以下内容:

# List of solvers
solvers = ["s1", "s2", "s3"]

# Wrapper for solvers
def Solver(choice, options):
    "Return solver instance for given choice"
    exec("from %s import Solver as ChosenSolver" % choice)
    return ChosenSolver(options)

主模块导入求解器和求解器,如下所示:

from solvers import Solver, solvers

对 的内容也采用了类似的方法__init__cases.py。它是为 Python 2.x 编写的。目录结构如下所示:

main/
  __init__.py
  mainmodule.py
  solversandcases/
    __init__solvers.py
    __init__cases.py
    basicsolver.py # where BasicSolver() class is defined
    basiccase.py # where BasicCase() class is defined
    s1.py # where Solver(BasicSolver) class is defined
    c1.py # where Case(BasicCase) class is defined

代码使用以下命令执行:

python2 mainmodule.py s1 c1

其中 s1 是求解器的选择,'c1' 是要运行的案例的选择。无异常运行并产生预期的输出。我只是不知道这实际上是如何工作的,官方文档中也没有关于将名称附加到__init__.py文件名的内容。谁能解释一下?

标签: pythoninit

解决方案


推荐阅读