我有两个类,第一个类有一个函数 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/