python - 如何修改软件架构来解决循环导入?

标签 python python-2.7 importerror

我目前正在编写一些用于人口模型模拟的 Python 2.7 代码,并且遇到了循环导入的问题。

该模型具有以下结构:

Island 类(在 landscape.py 中)

  • 带有坐标的景观单元格集合

Cell 类(在 landscape.py 中)

  • 所有景观单元的父类(super class)(丛林萨凡纳等)。细胞类别有一个字典,其中包含该细胞中的不同动物。
  • animal 字典的结构如下:

    animals = {AnimalType1: [animal1_inst_1, animal_2_inst_2],
               AnimalType2: [animal2_inst_1, animal_2_inst_2]}
    
  • 每个单元格的初始animal字典是在运行时设置的。

Animal 类(在 animals.py 中)

  • 所有动物类型的父类(super class)(目前只有草食动物食肉动物)。
  • 所有动物类都有一个类变量 allowed_cells,它是该动物可以驻留的所有细胞类型的列表,例如

    allowed_cells = [landscape.Jungle, landscape.Savannah]
    

我的问题是这样的 - Animals.py 被导入到 Landscape.py 中,以检查动物字典中的所有键是否都是 Animal 子类,以及相应列表中的所有实例是否都是该动物类的实例。在 animals.py 中,导入 landscape.py,以便除了其他地方的许多测试之外,allowed_cells 列表可以包含实际的细胞类。

当我尝试运行代码时,出现错误:

Traceback (most recent call last):
  File "C:/Users/yngve_000/Documents/INF200/inf200_dag_yngve/PA04/biosim/simulation.py", line 10, in <module>
    import landscape as landscape
  File "C:\Users\yngve_000\Documents\INF200\inf200_dag_yngve\PA04\biosim\landscape.py", line 12, in <module>
    import animals
  File "C:\Users\yngve_000\Documents\INF200\inf200_dag_yngve\PA04\biosim\animals.py", line 18, in <module>
    class Animal(object):
  File "C:\Users\yngve_000\Documents\INF200\inf200_dag_yngve\PA04\biosim\animals.py", line 70, in Animal
    allowed_cell_types = [landscape.Jungle, landscape.Desert,
AttributeError: 'module' object has no attribute 'Jungle'

我明白为什么会出现这个错误,但不知道如何以优雅的方式删除它。可以为 Animal 类创建一个 is_animal 函数,并使用 try/except 的一些解决方法,但这至少可以说是非常糟糕的。

解决这个问题的最佳方法是什么?

最佳答案

animals 导入 landscape 来定义动物可以居住的地方似乎很自然。另一方面,我不明白为什么在landscape中需要Animal。细胞可以(可能)在没有任何动物的情况下存在,但每个动物必须生活在细胞中。所以你应该尝试从landscape中删除动物的东西,并且这个模块应该只包含景观类。实例化应该在不同的模块中进行,并且在实例化时单元格中应该填充有动物。因此,让动物列表成为 __init__ 的参数。

请注意,您可以通过子类检查执行 is_animal 形式的检查。 IE。如果 Dog 继承自 Animal,则 issubclass(Dog, Animal) 的计算结果为 True。您还可以使用abstract base classesregister其他类作为子类。

关于python - 如何修改软件架构来解决循环导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41635100/

相关文章:

python - 包含同名类的 Python 模块在导入时如何工作?

python - Healpy python-3..4 在 ubuntu-14.04 上的安装问题

python - 将字符串文件转换为所需格式 : replace/with _ except the ones before comma

python-2.7 - Kerberos 安装后 Python Impyla 失败

python-2.7 - 将测试集分为子组,然后分别对每个子组进行预测

go - 无法识别的导入路径 "syscall/js"

python - Github api v3 通过 python oauth2 库访问 - 重定向问题

python - 使用不同的连接列外连接 Spark 数据框,然后合并连接列

python - wxPython导入错误

java导入错误 "the type android.widget.Filter.FilterResults is not visible"