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

标签 python oop methods pygame components

我知道这个标题听起来很困惑,但请耐心听我说。 我正在编写我的第一个游戏,我正在尝试为 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/

相关文章:

java - 如果单例很糟糕,那么如何存储框架的全局状态

java - apache tomcat java-web 服务上的 NoEndPointException()

php - 方法语法 "public function direct(){}"在 PHP 中如何工作?

python - 如何为这些 DNS 数据库方法创建 Python 类?

java - 使用方法更改现有数组的大小

c++ - 封装在组合类 C++ 中

python - 如何使用 "&"字符设置属性值

python - Django 数据表和枚举

python - 应用引擎 : "URLFetch is not available in this environment."

python - 如何更改Python的标准输入缓冲区大小?