0

这可能是一个愚蠢的问题,但无论如何我都会问它。我有一个生物文件和一个模拟文件,每个文件都包含一个同名的类。在 Simulation 类的 init 中,我需要初始化两个 Creature 对象。我已经导入了生物文件,但是当我尝试 bio.Creature() 我得到

Traceback (most recent call last):
  File "/Users/lego90511/Documents/workspace/creatureSim/simulation.py", line 2, in <module>
    import creature
  File "/Users/lego90511/Documents/workspace/creatureSim/creature.py", line 3, in <module>
    import simulation
  File "/Users/lego90511/Documents/workspace/creatureSim/simulation.py", line 86, in <module>
    sim = Simulation(5)        
  File "/Users/lego90511/Documents/workspace/creatureSim/simulation.py", line 6, in __init__
    self.creatures = {creature.Creature(4, 4, 3, 4, 4, 3, 10):"", creature.Creature(4, 4, 3, 4, 4, 3, 10):"", }
AttributeError: 'module' object has no attribute 'Creature'"

我究竟做错了什么?

以下是相关代码:

模拟:

import creature
from random import randint
class Simulation():
    def __init__(self, x):
        self.creatures = {creature.Creature():"", creature.Creature():"", }
        ...

生物:

class Creature:
    def __init__(self, social, intelligence, sensory, speed, bravery, strength, size):
        self.traits = [social, intelligence, sensory, speed, bravery, strength]
        ...
4

1 回答 1

2

你有一个循环依赖。creature正在 importing simulation,而后者又试图 import creature,所以它失败了。您需要以不同的方式构建文件以消除循环性 - 将两个类放在一个文件中,或者将一个导入移动到函数中。

于 2013-03-24T18:43:07.890 回答