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

2 投票
1 回答
3944 浏览
提问于 2025-04-17 20:06

我有两个类,第一个类里面有一个叫做move(creature, board)的函数。在creature类里面,有一个函数会调用move。那么在creature类里,我该怎么把当前的creature传给move函数呢?我是不是应该用move(self, self.board)?可是我试了之后,出现了“从导入中未定义的变量:move”的错误。

这是相关的代码:

Creature:

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
       ...

Simulation:

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)。我猜这意味着它不仅需要类文件,还需要这个类的一个实例。那么新问题是,我是否需要在别的地方创建这个实例,然后传递进去?还是说在其他地方的Simulation实例也能用?

1 个回答

2

simulation 类继承到 creature 类里:

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)

撰写回答