2

我有两个类,第一个有一个函数 move(creature, board)。然后在生物类中有一个调用move的函数,那么在生物类中如何将当前生物传递给move函数呢?它应该只是 move(self, self.board),因为当我尝试得到“来自导入的未定义变量:move”错误时?

以下是相关代码:

生物:

class creature: 
    def __init__(self, social, intelligence, sensory, speed, bravery, strenght, size):
        self.traits = [social, intelligence, sensory, speed, bravery, strenght]
        self.x = 0
        self.y = 0
        self.hunger = 10
        self.energy = 30
        self.shelter = 0
        self.dominance = 0
        self.boardSize = size - 1
        self.SOCIAL = 0
        self.INTELLIGENCE = 1
        self.SENSORY = 2
        self.SPEED = 3
        self.BRAVERY = 4
        self.STRENGTH = 5
 ...
 def performAction(self, action, location):
       ...     
       if action == "storeFood":
          food = location.vegetation
          location.vegetation = -1
          simulation.move(self, self.shelter)
          self.shelter.foodStorage += food
       ...

模拟:

class simulation():
    def __init__(self, x):
        self.creatures = {creature.creature():"", creature.creature():"", }
        self.map = land.landMass
        self.lifeCycles = x
        self.runStay = ["rfl", "rbf", "rbl", "rbf", ]
        self.befriend = ["bbl", "bbf"]
        self.fight = ["fbl", "fbf", "bfl", "bff", "ffl", "fff"]
...    
    def move(self, creature, target):
            map[creature.x][creature.y].creatures.remove(creature)
            creature.energy -= abs(map[creature.x][creature.y].elevation - target.elevation) / creature.getSpeed() 
            target.creatures.append(creature)
            creature.x, creature.y = target.location
            ...  

编辑:好的,所以我已经解决了这个问题。Python 需要simulation.simulation.map(self, self.shelter)我假设这意味着它不仅需要类文件,还需要该类的实例。所以新的问题是我是否必须在其他地方创建该实例然后将其传递?或者这是否适用于其他地方的模拟实例?

4

1 回答 1

2

将类继承simulationcreature类中:

class Creature(Simulation): # I have inherited the functions from Simulation into Creature
    ...

现在simulation.move(self, self.shelter),您想要的是:

self.move(yourparameters)

如果您注意到,我将您的班级名称大写。这样做很好。

有关类继承的更多信息,请查看 [查看文档]。(http://docs.python.org/2/tutorial/classes.html#inheritance

于 2013-03-24T05:10:50.440 回答