gpt4 book ai didi

python 将方法从 classB 作为参数传递给 classA,然后从传递的 classB 方法调用 classA 中的方法

转载 作者:行者123 更新时间:2023-12-01 00:33:33 25 4
gpt4 key购买 nike

我知道这个标题听起来很困惑,但请耐心听我说。我正在编写我的第一个游戏,我正在尝试为 AI 设置一个类(称为 AI_mode),我的 obj_creature 类可以使用它来获取生物实体所需的任何类型的 AI。我将一个方法从 AI_mode 作为变量传递给 obj_creature。从 AI_mode 传递到 obj_creature 的方法调用 obj_creature 类内部的另一个方法。这是一些精简的代码:

class obj_creature:
def __init__(self, npc_mode=None):
self.npc_mode=npc_mode

def move(self, word):
print(word)


class AI_mode:
def ai_move_left(self):
self.owner.move("Hello World")


enemy_ai=AI_mode().ai_move_left
enemy_creature=obj_creature(npc_mode=enemy_ai)


if enemy_creature.npc_mode:
enemy_creature.npc_mode()

此代码给出错误:

self.owner.move("Hello World")
AttributeError: 'AI_mode' object has no attribute 'owner'

我很确定 .owner() 不是正确的使用方式,因为我从未将 obj_creature 声明为所有者,但我不太确定在其位置使用什么。当我尝试将 obj_creature 声明为 AI_mode 的所有者时,如下所示:

class obj_creature:
def __init__(self, npc_mode=None):
self.npc_mode=npc_mode
if npc_mode:
npc_mode.owner=self

我收到此错误:

npc_mode.owner=self
AttributeError: 'method' object has no attribute 'owner'

我的最终目标是轻松地将同一类别的各种 AI 分配给任何类型的生物,并能够稍后使用相同的命令调用分配给它的任何 AI

最佳答案

找到下面的代码设计:

class obj_creature:
def __init__(self, npc_mode=None):
self.npc_mode=npc_mode

def move(self, word):
print(word)


class AI_mode:
def __init__(self, owner):
self.owner = owner

def ai_move_left(self):
self.owner.move("Hello World")


enemy_creature=obj_creature()
enemy_ai=AI_mode(enemy_creature)
enemy_creature.npc_mode=enemy_ai.ai_move_left

if enemy_creature.npc_mode:
enemy_creature.npc_mode()

关于python 将方法从 classB 作为参数传递给 classA,然后从传递的 classB 方法调用 classA 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57986007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com