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

标签 python class self

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

相关代码如下:

生物:

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

最佳答案

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 )

关于python - 将 self 传递给 self 函数中的另一个类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15594994/

相关文章:

python - 谁能解释一下 "out = self(images)"在下面的代码中做了什么

ios - 从其他类调用方法(自身问题)

python - 在 Oracle DB 上从 python 运行 set role 命令

python - 哪个异常通知子类应该实现一个方法?

python - 计算 Pandas 数据框中满足特定条件的行数

PHP 加速器和静态字段

java - Python self 和 Java this 的区别

python - 斐波那契常数倒数

java - 动态类加载时运行时注释扫描

sql - 使用 BasePage 打开和关闭 SQL 连接的安全性如何?