将self传递给另一个类函数在self的函数中

时间:2013-03-24 03:54:18

标签: python class self

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

以下是相关代码:

怪物:

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)我假设这意味着它不仅需要类文件,还需要该类的实例。所以新的问题是我必须在其他地方制作该实例然后传入吗?或者这可以在其他地方使用模拟实例吗?

1 个答案:

答案 0 :(得分:2)

simulation类继承到creature类:

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

现在代替simulation.move(self, self.shelter),您需要:

self.move(yourparameters)

如果您注意到,我将您的班级名称大写。 It's good to do so.

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